@civitai/app-sdk 0.86.0 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -95,19 +95,14 @@ import manifestSchema from '@civitai/app-sdk/schemas/app-block/v1.json' with { t
95
95
 
96
96
  A block runs in a sandboxed iframe. The host (civitai.com) and the block speak
97
97
  over `window.postMessage({ type, payload }, targetOrigin)`, discriminated by
98
- `type`. The full union is exported:
99
-
100
- - **parent → block**: `BLOCK_INIT`, `TOKEN_REFRESH`, `TOKEN_REFRESH_RESPONSE`,
101
- `ESTIMATE_RESULT`, `ESTIMATE_BATCH_RESULT`, `WORKFLOW_SUBMITTED`, `WORKFLOW_STATUS`,
102
- `BUZZ_PURCHASE_RESULT`, `CHECKPOINT_PICKER_RESULT`, `USER_CHECKPOINT_SET`,
103
- `APP_STORAGE_*_RESULT`, `SUSPEND`, `RESUME`, `THEME_CHANGE`, `ROUTE_CHANGED`,
104
- `CONSENT_UNAVAILABLE` (`ParentToBlockMessage`).
105
- - **block → parent**: `BLOCK_READY`, `BLOCK_ERROR`, `REQUEST_TOKEN`,
106
- `RESIZE_IFRAME`, `SUBMIT_WORKFLOW`, `ESTIMATE_WORKFLOW`,
107
- `ESTIMATE_WORKFLOW_BATCH`, `POLL_WORKFLOW`,
108
- `QUERY_APP_WORKFLOWS`, `CANCEL_APP_WORKFLOW`, `OPEN_BUZZ_PURCHASE`,
109
- `OPEN_CHECKPOINT_PICKER`, `SET_USER_CHECKPOINT`, `NAVIGATE`, `TRACK_EVENT`,
110
- `APP_STORAGE_*` (`BlockToParentMessage`).
98
+ `type`. Both unions are exported from `@civitai/app-sdk/blocks`, and their
99
+ source is the list — it is not copied here, so it cannot fall behind:
100
+
101
+ - **parent → block**: `ParentToBlockMessage` (`ParentToBlockMessageType` is its
102
+ `type` union), in
103
+ [`src/blocks/messages.ts`](https://github.com/civitai/civitai-app-starters/blob/main/packages/civitai-app-sdk/src/blocks/messages.ts).
104
+ - **block → parent**: `BlockToParentMessage` (`BlockToParentMessageType`), in the
105
+ same file; `BLOCK_TO_PARENT_MESSAGE_TYPES` is the same set as a runtime array.
111
106
 
112
107
  The app generator **subqueue** pair — `QUERY_APP_WORKFLOWS` →
113
108
  `APP_WORKFLOWS_RESULT` and `CANCEL_APP_WORKFLOW` → `CANCEL_APP_WORKFLOW_RESULT` —
@@ -117,6 +112,41 @@ forces the per-app tag filter off the block token, so a block only ever sees the
117
112
  queue it produced. Mirrors civitai/civitai PR #3164; the `@civitai/blocks-react`
118
113
  `useAppWorkflows()` hook wraps both.
119
114
 
115
+ `PERSIST_GENERATION_SOURCE` → `GENERATION_SOURCE_PERSISTED` saves ONE of those
116
+ outputs as a **private, scanned generation source** for the next generation.
117
+ The request is `{ requestId, workflowId, imageIndex }` (an index into the
118
+ workflow's `images`; never a url) and the reply carries `result`, a
119
+ `BlockPersistedGenerationSource` (`{ url, width, height, imageId, ready }`), or a
120
+ free-text `error`. The image is private to the viewer and not on the app's
121
+ shared grid, and there is no confirm dialog. The host waits up to about thirty
122
+ seconds for the scan; `ready: false` means it is still pending, and a generation using the
123
+ source is refused with `source-scan-pending` until it finishes. `url` / `width` /
124
+ `height` are a `BlockGenerationSourceImageInfo`, so they go into a
125
+ `sourceImages` entry (a `textToImage` source image is refused with
126
+ `source-scan-pending` too). It is idempotent per (viewer, app, `workflowId`,
127
+ `imageIndex`): asking again returns the same image with its current `ready`.
128
+ Full-page app hosts only: the iframe/slot host, review mode, a block that is not
129
+ ready yet and App Assistant dev-tunnel previews all reply with an `error`. The
130
+ `@civitai/blocks-react` `usePersistGenerationSource()` hook wraps it; its README
131
+ section lists the size and rate limits:
132
+
133
+ ```ts
134
+ import type { BlockPersistedGenerationSource, WorkflowBody } from '@civitai/app-sdk/blocks';
135
+
136
+ declare const src: BlockPersistedGenerationSource; // from persist({ workflowId, imageIndex: 0 })
137
+ declare const modelId: number, modelVersionId: number;
138
+
139
+ const next: WorkflowBody = {
140
+ kind: 'textToImage',
141
+ modelId,
142
+ modelVersionId,
143
+ params: { prompt: 'the same fox, in snow' },
144
+ sourceImages: [{ url: src.url, width: src.width, height: src.height }],
145
+ };
146
+ // If `src.ready` was false, submitting `next` can fail with errorCode
147
+ // 'source-scan-pending' (nothing is reserved); retry it later.
148
+ ```
149
+
120
150
  `isMessage(data, 'BLOCK_INIT')` is a **discriminator-only** narrowing helper — it
121
151
  checks `data.type`, NOT the payload shape. Anything crossing the iframe trust
122
152
  boundary must be payload-validated at the boundary (the React transport does this
@@ -153,7 +183,39 @@ interface BlockInitPayload {
153
183
  | `isModelSlotContext(ctx)` / `isPageSlotContext(ctx)` | Runtime narrowing for the `slotId`-discriminated `BlockContext` union. Real checks on a value that crossed a `postMessage` boundary — they verify every field they assert, not just `slotId`. |
154
184
  | `fetchNestedDocument(opts)` | Embed one of your OWN bundled documents as an iframe `srcdoc`, because a nested `<iframe src>` of your own content **cannot load** — see [Nested documents](#nested-documents) below. `NestedDocumentError` carries a `.code` of `'invalid-url' \| 'http-error' \| 'network-error'`. |
155
185
  | `isSignedIn(viewer)` | **The sign-in gate.** `isSignedIn(useBlockContext().viewer)` — do not open-code it as `viewer !== null` or `viewer?.signedIn === true`. Which of those is correct has already changed once with the host contract, and this is the one place it is decided. It reads neither `viewer.id` nor `viewer.username` (both `@deprecated`), so nothing written through it changes when those are removed. Need the identity rather than the presence? `useViewer()` — scope-gated and audited per call. |
156
- | types | `BlockManifestV1`, `ManifestSettings` (+ field types), `BlockContext`, `ModelSlotContext`, `BlockCheckpointInfo`, `ShowcaseImage`, `BlockToken`, `WrappedToken`, `BlockSettings`, `ViewerInfo`, `Theme`, `WorkflowBody`, `BlockTextToImageParams`, `WorkflowBodyCustomComfy` (+ its two arms `WorkflowBodyCustomComfyRecipe` / `WorkflowBodyCustomComfyInline`, and `InlineComfyNode`), `WorkflowBodyStep` / `WorkflowBodyPassThroughStep` (the two arms of `kind: 'step'`), `WorkflowBodyTraining` (+ `AiToolkitTrainingParams`, `BlockTrainingQuote`, `BlockTrainingDatasetItem`, `BlockTrainingDataImage`, `BlockTrainingDataUploadResult`, `BlockRunTrainingHostError` and the `BLOCK_TRAINING_*` bounds), `WorkflowBodyWorkflow` (+ `WorkflowBodyWorkflowStep`, `WorkflowStepRef`, `WithWorkflowStepRefs`, `BlockWorkflowStepSnapshot` and `BLOCK_WORKFLOW_MAX_STEPS`), `BlockStepQuote` / `BlockRunConfirmedStepHostError` (+ `BLOCK_CONFIRMED_STEP_MAX_BUZZ_PER_JOB`, `BLOCK_STEP_QUOTE_ID_REGEX`), `BlockModel3dOutput`, `BlockWorkflowSnapshot`, `WorkflowStatus`, `BlockInitPayload`, `ParentToBlockMessage`, `BlockToParentMessage`. |
186
+ | types | `BlockManifestV1`, `ManifestSettings` (+ field types), `BlockContext`, `ModelSlotContext`, `BlockCheckpointInfo`, `ShowcaseImage`, `BlockToken`, `WrappedToken`, `BlockSettings`, `ViewerInfo`, `Theme`, `WorkflowBody`, `BlockTextToImageParams`, `WorkflowBodyCustomComfy` (+ its two arms `WorkflowBodyCustomComfyRecipe` / `WorkflowBodyCustomComfyInline`, and `InlineComfyNode`), `WorkflowBodyStep` / `WorkflowBodyPassThroughStep` (the two arms of `kind: 'step'`), `WorkflowBodyTraining` (+ `AiToolkitTrainingParams`, `BlockTrainingQuote`, `BlockTrainingDatasetItem`, `BlockTrainingDataImage`, `BlockTrainingDataUploadResult`, `BlockRunTrainingHostError` and the `BLOCK_TRAINING_*` bounds), `WorkflowBodyWorkflow` (+ `WorkflowBodyWorkflowStep`, `WorkflowStepRef`, `WithWorkflowStepRefs`, `BlockWorkflowStepSnapshot` and `BLOCK_WORKFLOW_MAX_STEPS`), `BlockStepQuote` / `BlockRunConfirmedStepHostError` (+ `BLOCK_CONFIRMED_STEP_MAX_BUZZ_PER_JOB`, `BLOCK_STEP_QUOTE_ID_REGEX`), `BlockModel3dOutput`, `BlockWorkflowSnapshot` (+ `BlockWorkflowEta`, `BlockWorkflowStepQueue` and `KnownBlockWorkflowQueueSupport` — queue position, ETA and progress, see below), `WorkflowStatus`, `BlockInitPayload`, `ParentToBlockMessage`, `BlockToParentMessage`. |
187
+
188
+ **Queue position, ETA and progress.** A non-terminal workflow snapshot from a
189
+ poll can carry `eta`, a summary of the step that is queued or running now, for
190
+ every kind of workflow. Each entry of `steps` can carry `queue` (only while that
191
+ step is queued), `progress`, `startedAt` and `completedAt`. All of them are
192
+ optional, and **absent means the same as `null`**: the host omits a field with
193
+ nothing to report. A terminal snapshot has no `eta`, nor does a host that
194
+ predates the field. A poll the host could not serve (rate-limited) answers
195
+ `{ workflowId, status: 'processing', throttled: true }`: not a real update, and
196
+ `@civitai/blocks-react`'s `watch` skips it. A throttled answer to a cancel means
197
+ the cancel was not issued: `useBuzzWorkflow().cancel()` rejects with
198
+ `WorkflowCancelNotIssuedError`; retry it. `progress` is a fraction from 0 to 1, reported only for image and
199
+ video generation steps. `queuedAhead` / `precedingJobs` count the jobs ahead in
200
+ the queue; while a step is queued they refresh at most once per held poll
201
+ (about every 15 s), since a held poll does not wake on queue drift. Every time
202
+ is an ISO-8601 string and an estimate. `support` is `'available' |
203
+ 'unavailable' | 'unsupported'` or a value added later (`'unavailable'` means no
204
+ capacity right now):
205
+
206
+ ```ts
207
+ import type { BlockWorkflowSnapshot } from '@civitai/app-sdk/blocks';
208
+
209
+ function etaLine(snapshot: BlockWorkflowSnapshot): string | null {
210
+ const eta = snapshot.eta;
211
+ if (!eta) return null; // terminal, or nothing queued or running
212
+ if (eta.progress !== null) return eta.progress.toLocaleString(undefined, { style: 'percent' });
213
+ const at = eta.startsAt
214
+ ? new Date(eta.startsAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
215
+ : null;
216
+ return `${eta.queuedAhead ?? '?'} ahead${at ? `, starts ~${at}` : ''}`;
217
+ }
218
+ ```
157
219
 
158
220
  `WorkflowBody`'s `customComfy` member is a discriminated union on `mode`, mirroring
159
221
  the host's `blockCustomComfyMemberSchema`. Narrow on the VALUE (`body.mode === 'inline'`),
@@ -228,6 +290,18 @@ const body: WorkflowBody = {
228
290
  };
229
291
  ```
230
292
 
293
+ **Choosing the Buzz pool.** Both step arms, and a `kind: 'workflow'` body (once for the whole
294
+ workflow, never per step), take an optional `accountType` (`'blue' | 'green' | 'yellow'`), as a
295
+ `textToImage` body does. The host tries that pool first and keeps the app's other allowed pools
296
+ as fallback — an SFW app may spend `blue` and `green`, a mature app `blue` and `yellow`. A pool
297
+ outside that set is refused on the estimate and the submit alike; omit the field for the
298
+ default order, blue first. A pick does **not** guarantee an unrestricted output: when the picked
299
+ pool runs out the fallback pays, and a fallback to `blue` can still leave a mature output
300
+ restricted. On a confirmed step, `accountType` is part of the quoted body — submit with the pool
301
+ you estimated with. **Release order: host first** — civitai/civitai must accept the field
302
+ (civitai/civitai#8985) before an app sends it, because a host that predates it refuses the whole
303
+ body as an unknown key. Leaving it out works on every host.
304
+
231
305
  **Above the per-call budget: a confirmed step.** A pass-through job the per-call budget refuses
232
306
  can still run when the **viewer confirms its exact price** in Civitai's own dialog
233
307
  (civitai/civitai#5786). When the orchestrator quotes a **fixed** price (positive, not variable
@@ -469,8 +543,8 @@ round-trip probe shows they're unusable. Rules:
469
543
  not propagated.
470
544
  - The fallback is **session-scoped** — nothing survives a reload. That's the
471
545
  honest semantic at an opaque origin. Treat storage as a cache; use the
472
- platform's app-storage messages (`useAppStorage` in `@civitai/blocks-react`)
473
- for anything durable.
546
+ document store (`app.storage.collection(name)` in `@civitai/sdk`) for anything
547
+ durable.
474
548
 
475
549
  Most apps need to do nothing. Two cases where you reach for it explicitly:
476
550
 
@@ -615,10 +689,98 @@ on one path):
615
689
  body returns your `maxBuzz` as `cost.total`, and billing settles to the real GPU
616
690
  time after the run. Show it as "up to N Buzz".
617
691
 
692
+ ### Sampler options per model family (`fetchGenerationSamplers`)
693
+
694
+ `params.sampler` on a `textToImage` body is a free string, and the valid names
695
+ depend on the model family: the SD families take `Euler a`, Chroma takes
696
+ `Euler`, Anima takes ComfyUI names such as `euler_ancestral`, and Flux.1 takes
697
+ no sampler at all. **A name the family does not offer is not refused.** The host
698
+ swaps in the family default, so a guessed sampler generates with a different one
699
+ and reports no error. Don't copy a list into your app. Read the one the on-site
700
+ generator renders:
701
+
702
+ ```ts
703
+ import { fetchGenerationSamplers, resolveGenerationSampler } from '@civitai/app-sdk/blocks';
704
+
705
+ // hostOrigin: useHostOrigin(); token: useBlockToken().raw — any block token works, no scope needed.
706
+ const catalog = await fetchGenerationSamplers({ hostOrigin, token });
707
+
708
+ // checkpoint: the checkpoint you generate against — a model block's
709
+ // context.checkpoint (BlockCheckpointInfo), or a page block's Checkpoint pick.
710
+ const lookup = resolveGenerationSampler(catalog, {
711
+ baseModel: checkpoint.baseModel,
712
+ modelVersionId: checkpoint.versionId,
713
+ });
714
+ if (!lookup.known) {
715
+ // The platform has no answer for this model (lookup.reason). Keep a free-text field.
716
+ } else if (lookup.sampler === null) {
717
+ // The generator shows no sampler control for this model: send no `sampler`.
718
+ } else {
719
+ // A drop-down: lookup.sampler.options ({ value, label }[]), preselect lookup.sampler.default.
720
+ }
721
+ ```
722
+
723
+ The route is `GET /api/v1/blocks/generation-samplers`. It returns
724
+ `{ ecosystems, baseModels }`:
725
+
726
+ - `ecosystems[key]` is `{ sampler, byModelVersion }`, keyed by ecosystem key.
727
+ `sampler` is `{ options, default }` or `null`. `byModelVersion[versionId]`
728
+ overrides it for model versions that select a different graph variant; today
729
+ that is HiDream Full, which offers `UniPC` while the rest of HiDream has no
730
+ sampler.
731
+ - `baseModels[name]` maps a base model name (`SDXL 1.0`, `Flux.1 D`, …) to its
732
+ ecosystem key.
733
+
734
+ `resolveGenerationSampler` applies them in this order:
735
+
736
+ 1. With `baseModel`, it finds the family, then that family's override for
737
+ `modelVersionId`, and otherwise the family's control. This matches the host,
738
+ which picks the graph by the checkpoint's base model and version.
739
+
740
+ 🔴 **Pass the CHECKPOINT, not a LoRA.** The host keys the sampler on the
741
+ checkpoint it generates against. A LoRA pick carries its own `baseModel` and
742
+ `versionId`, and a LoRA install's resolved checkpoint can belong to a different
743
+ family, so looking up the LoRA can show the wrong list. The host then swaps a
744
+ sampler from that list for the checkpoint family's default.
745
+ 2. With only `modelVersionId`, it uses the override that lists that version.
746
+ A version with no override needs `baseModel`.
747
+
748
+ An override of `null` means that version has no sampler. It does not fall
749
+ through to the family.
750
+
751
+ 🔴 **Unknown is not "no sampler".** A family the platform could not determine
752
+ is absent from `ecosystems`, never `null`, and the platform maps no base model
753
+ to it. `resolveGenerationSampler` reports that as `{ known: false, reason }`,
754
+ and that arm has no `sampler` property, so TypeScript makes you narrow on
755
+ `known` first. The reasons are:
756
+
757
+ - `base-model-not-in-catalog`: the base model is not in `baseModels`. This is
758
+ what a family the platform could not determine looks like, as well as a base
759
+ model the platform does not map at all.
760
+ - `family-not-in-catalog`: the base model maps to a family missing from
761
+ `ecosystems`. The platform does not send that combination. You get it when
762
+ `parseGenerationSamplers` dropped a family it could not read, or from a
763
+ catalog you built yourself.
764
+ - `base-model-required`: only a version id was given and it has no override.
765
+
766
+ **On a platform without the route**, `fetchGenerationSamplers` throws
767
+ `GenerationSamplersError` with `code: 'unsupported-platform'`, after the host
768
+ answers `404`. It never resolves to an empty catalog, which would read as "no
769
+ family has a sampler". The other codes are:
770
+
771
+ - `unauthorized` (`401`/`403`, a bad or expired block token);
772
+ - `http-error` (any other non-2xx);
773
+ - `invalid-response` (a 2xx that is not the catalog);
774
+ - `network-error` (the fetch itself failed).
775
+
776
+ An abort before the response arrives rejects with the `AbortError`. An abort
777
+ while the body is being read surfaces as `invalid-response`.
778
+
618
779
  ### Version compatibility
619
780
 
620
781
  | `@civitai/app-sdk` | adds (blocks surface) |
621
782
  |---|---|
783
+ | `0.87.0` | `fetchGenerationSamplers` / `resolveGenerationSampler` / `parseGenerationSamplers` / `GenerationSamplersError`: the on-site generator's sampler options per model family (needs a platform that serves `GET /api/v1/blocks/generation-samplers`) |
622
784
  | `0.80.0` | `checkComfyGraph` — pre-spend check that a workflow file can run as an inline `customComfy` graph; `BLOCK_INLINE_COMFY_MAX_NODES` / `BLOCK_INLINE_COMFY_MAX_GRAPH_BYTES` |
623
785
  | `0.57.0` | `fetchNestedDocument` / `NestedDocumentError` — the `srcdoc` escape hatch for embedding your own bundled documents |
624
786
  | `0.27.0` | `@civitai/app-sdk/safe-storage` — opaque-origin `localStorage`/`sessionStorage` shim, auto-installed by the `blocks` subpath |
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Sampler options per model family — the list the on-site generator shows in
3
+ * its sampler drop-down, read from `GET /api/v1/blocks/generation-samplers`.
4
+ *
5
+ * WHY THIS EXISTS. A block's `textToImage` body takes `params.sampler` as a
6
+ * free string, and which names are valid depends on the model family (the SD
7
+ * families, Chroma, Anima's ComfyUI names, a HiDream variant…). A name the
8
+ * family does not offer is not refused: the host replaces it with the family
9
+ * default, so a guessed sampler silently generates with a different one. A
10
+ * list copied into an app drifts. The platform serves the generator's own
11
+ * list instead, derived from the same source the generator renders.
12
+ *
13
+ * WIRE SHAPE (any valid block token; no scope needed):
14
+ *
15
+ * { ecosystems: { [ecosystemKey]: { sampler: { options, default } | null,
16
+ * byModelVersion: { [versionId]: { options, default } | null } } },
17
+ * baseModels: { [baseModelName]: ecosystemKey } }
18
+ *
19
+ * THREE ANSWERS, NEVER TWO. For a given model the catalog says one of:
20
+ * - `{ options, default }` — the family (or this model version) has a sampler
21
+ * control; offer exactly these values.
22
+ * - `null` — the generator shows NO sampler control for it (Flux.1, for one).
23
+ * Send no `sampler`.
24
+ * - absent — the platform could not determine the family, or does not map
25
+ * this base model. That is "unknown", and {@link resolveGenerationSampler}
26
+ * reports it as `known: false` so it can never be read as "no sampler".
27
+ *
28
+ * OLD PLATFORM. A civitai.com that predates the route answers `404`. The getter
29
+ * throws {@link GenerationSamplersError} with `code: 'unsupported-platform'`
30
+ * rather than resolving to an empty catalog, because an empty catalog would
31
+ * read as "no family has a sampler".
32
+ */
33
+ /** The block REST route this module reads. Resolved against the host origin. */
34
+ export declare const GENERATION_SAMPLERS_API_PATH = "/api/v1/blocks/generation-samplers";
35
+ /** One drop-down entry. Send `value` as `params.sampler`; show `label`. */
36
+ export interface GenerationSamplerOption {
37
+ value: string;
38
+ label: string;
39
+ }
40
+ /** A sampler control: its options in the generator's order, plus the value a fresh form preselects. */
41
+ export interface GenerationSamplerField {
42
+ options: GenerationSamplerOption[];
43
+ default: string;
44
+ }
45
+ /** One model family (keyed by ecosystem key in {@link GenerationSamplerCatalog.ecosystems}). */
46
+ export interface GenerationSamplerFamily {
47
+ /** The family's sampler control, or `null` when the generator shows none. */
48
+ sampler: GenerationSamplerField | null;
49
+ /**
50
+ * Per-model-version overrides, keyed by model version id (as a string). A
51
+ * version listed here selects a graph variant whose sampler control differs
52
+ * from the family's; `null` means that version has none. It takes precedence
53
+ * over {@link sampler}.
54
+ */
55
+ byModelVersion: Record<string, GenerationSamplerField | null>;
56
+ }
57
+ /** What {@link fetchGenerationSamplers} resolves to. */
58
+ export interface GenerationSamplerCatalog {
59
+ /** Families by ecosystem key. A family the platform could not determine is ABSENT, never `null`. */
60
+ ecosystems: Record<string, GenerationSamplerFamily>;
61
+ /** Base model name (a checkpoint's `baseModel`) → ecosystem key. Only families present in `ecosystems` are mapped. */
62
+ baseModels: Record<string, string>;
63
+ }
64
+ /** Why {@link fetchGenerationSamplers} failed. */
65
+ export type GenerationSamplersErrorCode =
66
+ /** `404`: this platform does not serve the route yet (or `hostOrigin` is not civitai.com). */
67
+ 'unsupported-platform'
68
+ /** `401`/`403`: the block token is missing, expired or invalid. */
69
+ | 'unauthorized'
70
+ /** Any other non-2xx status. */
71
+ | 'http-error'
72
+ /** A 2xx whose body is not the catalog shape. */
73
+ | 'invalid-response'
74
+ /** The fetch itself failed — offline, DNS, TLS, CORS, no `fetch` global. */
75
+ | 'network-error';
76
+ /** Thrown by {@link fetchGenerationSamplers}. Branch on `code`, not on the message. */
77
+ export declare class GenerationSamplersError extends Error {
78
+ readonly name = "GenerationSamplersError";
79
+ readonly code: GenerationSamplersErrorCode;
80
+ /** HTTP status, when the host answered. */
81
+ readonly status: number | undefined;
82
+ constructor(message: string, options: {
83
+ code: GenerationSamplersErrorCode;
84
+ status?: number | undefined;
85
+ cause?: unknown;
86
+ });
87
+ }
88
+ /** Options for {@link fetchGenerationSamplers}. */
89
+ export interface FetchGenerationSamplersOptions {
90
+ /** The validated host origin, e.g. `useHostOrigin()` from `@civitai/blocks-react`. */
91
+ hostOrigin: string;
92
+ /** The raw block token, e.g. `useBlockToken().raw`. Any valid block token works. */
93
+ token: string;
94
+ /** Abort the request. Rejects with the underlying `AbortError`, not a `GenerationSamplersError`. */
95
+ signal?: AbortSignal;
96
+ /** Override `fetch` (tests, or a runtime without a global one). */
97
+ fetch?: typeof fetch;
98
+ }
99
+ /**
100
+ * Validate a response body into a {@link GenerationSamplerCatalog}. Exported for
101
+ * a caller that does its own fetch (for example through `@civitai/sdk`).
102
+ *
103
+ * A malformed family is DROPPED, so it reads as unknown — the same answer the
104
+ * platform gives for a family it could not determine. Unknown extra fields are
105
+ * ignored. Throws `GenerationSamplersError` (`invalid-response`) only when the
106
+ * body is not the catalog shape at all.
107
+ */
108
+ export declare function parseGenerationSamplers(body: unknown): GenerationSamplerCatalog;
109
+ /**
110
+ * Fetch the per-family sampler catalog with a block token.
111
+ *
112
+ * Throws {@link GenerationSamplersError}; on a platform without the route that
113
+ * is `code: 'unsupported-platform'`, never an empty catalog.
114
+ *
115
+ * @example
116
+ * const catalog = await fetchGenerationSamplers({ hostOrigin, token: raw });
117
+ * // checkpoint: the checkpoint you generate against (a model block's context.checkpoint), never a LoRA.
118
+ * const lookup = resolveGenerationSampler(catalog, { baseModel: checkpoint.baseModel, modelVersionId: checkpoint.versionId });
119
+ */
120
+ export declare function fetchGenerationSamplers(opts: FetchGenerationSamplersOptions): Promise<GenerationSamplerCatalog>;
121
+ /**
122
+ * Which model to look up: the CHECKPOINT you generate against (`BlockCheckpointInfo`, or a
123
+ * Checkpoint pick), never a LoRA. The host keys the sampler on the checkpoint, and a LoRA can
124
+ * belong to a different family.
125
+ */
126
+ export interface GenerationSamplerLookupInput {
127
+ baseModel?: string | null | undefined;
128
+ modelVersionId?: number | null | undefined;
129
+ }
130
+ /** Why {@link resolveGenerationSampler} could not answer. */
131
+ export type GenerationSamplerUnknownReason =
132
+ /** The catalog does not map this base model to a family. */
133
+ 'base-model-not-in-catalog'
134
+ /**
135
+ * The base model maps to a family absent from `ecosystems`. The platform never sends this
136
+ * (it maps no base model to a family it could not determine, so that case is
137
+ * `base-model-not-in-catalog`); it comes from a family the parser dropped, or a hand-built catalog.
138
+ */
139
+ | 'family-not-in-catalog'
140
+ /** Only a model version id was given, and it has no per-version override, so the family is unknown. */
141
+ | 'base-model-required';
142
+ /**
143
+ * What {@link resolveGenerationSampler} returns. Narrow on `known` before
144
+ * reading `sampler`: an unknown result has no `sampler` at all, so it cannot be
145
+ * mistaken for `null` ("this model has no sampler control").
146
+ */
147
+ export type GenerationSamplerLookup = {
148
+ known: true;
149
+ /** The control to render, or `null` when the generator shows none — send no `sampler`. */
150
+ sampler: GenerationSamplerField | null;
151
+ /** The family's ecosystem key. */
152
+ ecosystem: string;
153
+ /** Whether the answer came from a per-version override or the family. */
154
+ source: 'modelVersion' | 'family';
155
+ } | {
156
+ known: false;
157
+ reason: GenerationSamplerUnknownReason;
158
+ };
159
+ /**
160
+ * Look up the sampler control for one model. Precedence:
161
+ *
162
+ * 1. With `baseModel`: its family, then that family's override for
163
+ * `modelVersionId` if it lists one, else the family's control. This matches
164
+ * the host, which picks the graph by the checkpoint's base model.
165
+ * 2. With `modelVersionId` only: the override that lists it, in whichever
166
+ * family. A version with no override needs `baseModel`.
167
+ *
168
+ * An override of `null` means that version has no sampler control; it does not
169
+ * fall through to the family.
170
+ */
171
+ export declare function resolveGenerationSampler(catalog: GenerationSamplerCatalog, input: GenerationSamplerLookupInput): GenerationSamplerLookup;
172
+ //# sourceMappingURL=generationSamplers.d.ts.map
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Sampler options per model family — the list the on-site generator shows in
3
+ * its sampler drop-down, read from `GET /api/v1/blocks/generation-samplers`.
4
+ *
5
+ * WHY THIS EXISTS. A block's `textToImage` body takes `params.sampler` as a
6
+ * free string, and which names are valid depends on the model family (the SD
7
+ * families, Chroma, Anima's ComfyUI names, a HiDream variant…). A name the
8
+ * family does not offer is not refused: the host replaces it with the family
9
+ * default, so a guessed sampler silently generates with a different one. A
10
+ * list copied into an app drifts. The platform serves the generator's own
11
+ * list instead, derived from the same source the generator renders.
12
+ *
13
+ * WIRE SHAPE (any valid block token; no scope needed):
14
+ *
15
+ * { ecosystems: { [ecosystemKey]: { sampler: { options, default } | null,
16
+ * byModelVersion: { [versionId]: { options, default } | null } } },
17
+ * baseModels: { [baseModelName]: ecosystemKey } }
18
+ *
19
+ * THREE ANSWERS, NEVER TWO. For a given model the catalog says one of:
20
+ * - `{ options, default }` — the family (or this model version) has a sampler
21
+ * control; offer exactly these values.
22
+ * - `null` — the generator shows NO sampler control for it (Flux.1, for one).
23
+ * Send no `sampler`.
24
+ * - absent — the platform could not determine the family, or does not map
25
+ * this base model. That is "unknown", and {@link resolveGenerationSampler}
26
+ * reports it as `known: false` so it can never be read as "no sampler".
27
+ *
28
+ * OLD PLATFORM. A civitai.com that predates the route answers `404`. The getter
29
+ * throws {@link GenerationSamplersError} with `code: 'unsupported-platform'`
30
+ * rather than resolving to an empty catalog, because an empty catalog would
31
+ * read as "no family has a sampler".
32
+ */
33
+ /** The block REST route this module reads. Resolved against the host origin. */
34
+ export const GENERATION_SAMPLERS_API_PATH = '/api/v1/blocks/generation-samplers';
35
+ /** Thrown by {@link fetchGenerationSamplers}. Branch on `code`, not on the message. */
36
+ export class GenerationSamplersError extends Error {
37
+ name = 'GenerationSamplersError';
38
+ code;
39
+ /** HTTP status, when the host answered. */
40
+ status;
41
+ constructor(message, options) {
42
+ super(message, { cause: options.cause });
43
+ this.code = options.code;
44
+ this.status = options.status;
45
+ }
46
+ }
47
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
48
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
49
+ /** A dictionary with no prototype, so a key like `constructor` or `__proto__` is just a key. */
50
+ function dict() {
51
+ return Object.create(null);
52
+ }
53
+ /** `undefined` = malformed. `null` is a valid value ("no sampler control"). */
54
+ function parseField(v) {
55
+ if (v === null)
56
+ return null;
57
+ if (!isRecord(v) || !Array.isArray(v.options) || typeof v.default !== 'string')
58
+ return undefined;
59
+ const options = [];
60
+ for (const o of v.options) {
61
+ if (!isRecord(o) || typeof o.value !== 'string' || typeof o.label !== 'string')
62
+ return undefined;
63
+ options.push({ value: o.value, label: o.label });
64
+ }
65
+ return { options, default: v.default };
66
+ }
67
+ function parseFamily(v) {
68
+ if (!isRecord(v) || !isRecord(v.byModelVersion))
69
+ return undefined;
70
+ const sampler = parseField(v.sampler);
71
+ if (sampler === undefined)
72
+ return undefined;
73
+ const byModelVersion = dict();
74
+ for (const [id, raw] of Object.entries(v.byModelVersion)) {
75
+ const field = parseField(raw);
76
+ // One malformed override drops the WHOLE family: keeping the rest would let
77
+ // that version fall through to the family's control, which is the wrong answer.
78
+ if (field === undefined)
79
+ return undefined;
80
+ byModelVersion[id] = field;
81
+ }
82
+ return { sampler, byModelVersion };
83
+ }
84
+ /**
85
+ * Validate a response body into a {@link GenerationSamplerCatalog}. Exported for
86
+ * a caller that does its own fetch (for example through `@civitai/sdk`).
87
+ *
88
+ * A malformed family is DROPPED, so it reads as unknown — the same answer the
89
+ * platform gives for a family it could not determine. Unknown extra fields are
90
+ * ignored. Throws `GenerationSamplersError` (`invalid-response`) only when the
91
+ * body is not the catalog shape at all.
92
+ */
93
+ export function parseGenerationSamplers(body) {
94
+ if (!isRecord(body) || !isRecord(body.ecosystems) || !isRecord(body.baseModels)) {
95
+ throw new GenerationSamplersError('generation-samplers: the response is not { ecosystems, baseModels }.', { code: 'invalid-response' });
96
+ }
97
+ const ecosystems = dict();
98
+ for (const [key, raw] of Object.entries(body.ecosystems)) {
99
+ const family = parseFamily(raw);
100
+ if (family)
101
+ ecosystems[key] = family;
102
+ }
103
+ const baseModels = dict();
104
+ for (const [name, key] of Object.entries(body.baseModels)) {
105
+ if (typeof key === 'string')
106
+ baseModels[name] = key;
107
+ }
108
+ return { ecosystems, baseModels };
109
+ }
110
+ /**
111
+ * Fetch the per-family sampler catalog with a block token.
112
+ *
113
+ * Throws {@link GenerationSamplersError}; on a platform without the route that
114
+ * is `code: 'unsupported-platform'`, never an empty catalog.
115
+ *
116
+ * @example
117
+ * const catalog = await fetchGenerationSamplers({ hostOrigin, token: raw });
118
+ * // checkpoint: the checkpoint you generate against (a model block's context.checkpoint), never a LoRA.
119
+ * const lookup = resolveGenerationSampler(catalog, { baseModel: checkpoint.baseModel, modelVersionId: checkpoint.versionId });
120
+ */
121
+ export async function fetchGenerationSamplers(opts) {
122
+ const doFetch = opts.fetch ?? (typeof fetch === 'function' ? fetch : undefined);
123
+ if (!doFetch) {
124
+ throw new GenerationSamplersError('generation-samplers: no fetch implementation available.', {
125
+ code: 'network-error',
126
+ });
127
+ }
128
+ if (!opts.hostOrigin) {
129
+ throw new TypeError('fetchGenerationSamplers: hostOrigin is required (wait for BLOCK_INIT).');
130
+ }
131
+ const url = new URL(GENERATION_SAMPLERS_API_PATH, opts.hostOrigin).toString();
132
+ let res;
133
+ try {
134
+ res = await doFetch(url, {
135
+ headers: { Authorization: `Bearer ${opts.token}` },
136
+ ...(opts.signal ? { signal: opts.signal } : {}),
137
+ });
138
+ }
139
+ catch (err) {
140
+ if (opts.signal?.aborted)
141
+ throw err;
142
+ throw new GenerationSamplersError('generation-samplers: the request failed before a response.', {
143
+ code: 'network-error',
144
+ cause: err,
145
+ });
146
+ }
147
+ if (res.status === 404) {
148
+ throw new GenerationSamplersError(`generation-samplers: ${url} answered 404. This Civitai platform does not serve the ` +
149
+ 'sampler catalog yet (or hostOrigin is not the Civitai host). Treat samplers as unknown; ' +
150
+ 'do not read this as "no samplers".', { code: 'unsupported-platform', status: 404 });
151
+ }
152
+ if (res.status === 401 || res.status === 403) {
153
+ throw new GenerationSamplersError(`generation-samplers: ${res.status} — the block token is missing, expired or invalid.`, { code: 'unauthorized', status: res.status });
154
+ }
155
+ if (!res.ok) {
156
+ throw new GenerationSamplersError(`generation-samplers: HTTP ${res.status}.`, {
157
+ code: 'http-error',
158
+ status: res.status,
159
+ });
160
+ }
161
+ let body;
162
+ try {
163
+ body = await res.json();
164
+ }
165
+ catch (err) {
166
+ throw new GenerationSamplersError('generation-samplers: the response is not JSON.', {
167
+ code: 'invalid-response',
168
+ status: res.status,
169
+ cause: err,
170
+ });
171
+ }
172
+ return parseGenerationSamplers(body);
173
+ }
174
+ /**
175
+ * Look up the sampler control for one model. Precedence:
176
+ *
177
+ * 1. With `baseModel`: its family, then that family's override for
178
+ * `modelVersionId` if it lists one, else the family's control. This matches
179
+ * the host, which picks the graph by the checkpoint's base model.
180
+ * 2. With `modelVersionId` only: the override that lists it, in whichever
181
+ * family. A version with no override needs `baseModel`.
182
+ *
183
+ * An override of `null` means that version has no sampler control; it does not
184
+ * fall through to the family.
185
+ */
186
+ export function resolveGenerationSampler(catalog, input) {
187
+ const versionKey = input.modelVersionId == null ? undefined : String(input.modelVersionId);
188
+ if (input.baseModel != null) {
189
+ if (!hasOwn(catalog.baseModels, input.baseModel)) {
190
+ return { known: false, reason: 'base-model-not-in-catalog' };
191
+ }
192
+ const ecosystem = catalog.baseModels[input.baseModel];
193
+ if (!hasOwn(catalog.ecosystems, ecosystem)) {
194
+ return { known: false, reason: 'family-not-in-catalog' };
195
+ }
196
+ const family = catalog.ecosystems[ecosystem];
197
+ if (versionKey !== undefined && hasOwn(family.byModelVersion, versionKey)) {
198
+ return { known: true, sampler: family.byModelVersion[versionKey], ecosystem, source: 'modelVersion' };
199
+ }
200
+ return { known: true, sampler: family.sampler, ecosystem, source: 'family' };
201
+ }
202
+ if (versionKey !== undefined) {
203
+ for (const [ecosystem, family] of Object.entries(catalog.ecosystems)) {
204
+ if (hasOwn(family.byModelVersion, versionKey)) {
205
+ return { known: true, sampler: family.byModelVersion[versionKey], ecosystem, source: 'modelVersion' };
206
+ }
207
+ }
208
+ }
209
+ return { known: false, reason: 'base-model-required' };
210
+ }
211
+ //# sourceMappingURL=generationSamplers.js.map
@@ -2,7 +2,7 @@
2
2
  * The IDEMPOTENCY-KEY FORMAT the host enforces on every money POST — **the only
3
3
  * site in this repository that spells this rule**.
4
4
  *
5
- * Sibling of `./appStorageLimits.ts`, for the same reason: the rule lives in the
5
+ * The rule lives in the
6
6
  * host, the SDK cannot change it, and a hand-copied regex at each call site is
7
7
  * how the copies come to agree with each other and disagree with the host.
8
8
  *
@@ -2,7 +2,7 @@
2
2
  * The IDEMPOTENCY-KEY FORMAT the host enforces on every money POST — **the only
3
3
  * site in this repository that spells this rule**.
4
4
  *
5
- * Sibling of `./appStorageLimits.ts`, for the same reason: the rule lives in the
5
+ * The rule lives in the
6
6
  * host, the SDK cannot change it, and a hand-copied regex at each call site is
7
7
  * how the copies come to agree with each other and disagree with the host.
8
8
  *