@literary-universe/sdk 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +336 -2
- package/dist/cjs/generated.d.ts +377 -0
- package/dist/cjs/generated.js +19 -0
- package/dist/cjs/imagePolicy.d.ts +89 -0
- package/dist/cjs/imagePolicy.js +104 -0
- package/dist/cjs/imageProcessing.d.ts +27 -0
- package/dist/cjs/imageProcessing.js +278 -0
- package/dist/cjs/imageWorker.cjs +79 -0
- package/dist/cjs/imageWorker.d.cts +5 -0
- package/dist/cjs/images.d.ts +6 -0
- package/dist/cjs/images.js +42 -0
- package/dist/cjs/index.d.ts +316 -0
- package/dist/cjs/index.js +366 -0
- package/dist/cjs/json.d.ts +3 -0
- package/dist/cjs/json.js +2 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/project.d.ts +51 -0
- package/dist/cjs/project.js +298 -0
- package/dist/esm/generated.d.ts +377 -0
- package/dist/esm/generated.js +16 -0
- package/dist/esm/imagePolicy.d.ts +89 -0
- package/dist/esm/imagePolicy.js +101 -0
- package/dist/esm/imageProcessing.d.ts +27 -0
- package/dist/esm/imageProcessing.js +271 -0
- package/dist/esm/imageWorker.cjs +79 -0
- package/dist/esm/imageWorker.d.cts +5 -0
- package/dist/esm/images.d.ts +6 -0
- package/dist/esm/images.js +37 -0
- package/dist/esm/index.d.ts +316 -0
- package/dist/esm/index.js +360 -0
- package/dist/esm/json.d.ts +3 -0
- package/dist/esm/json.js +1 -0
- package/dist/esm/project.d.ts +51 -0
- package/dist/esm/project.js +292 -0
- package/image-policy.json +72 -0
- package/package.json +84 -4
- package/schema.graphql +331 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Literary Universe contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,337 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Literary Universe SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript and JavaScript client for the [Literary Universe](https://literaryuniverse.com)
|
|
4
|
+
authoring API. Use it to read your writing, save versioned drafts, create and
|
|
5
|
+
publish chapters, manage universe translations, and prepare or upload images.
|
|
6
|
+
The [CLI](https://github.com/LiteraryUniverse/cli) uses this SDK; Obsidian and local
|
|
7
|
+
MCP integrations can use the same client.
|
|
8
|
+
|
|
9
|
+
Read the [documentation in our feedback knowledge base](https://literaryuniverse.com/feedback/help)
|
|
10
|
+
for Literary Universe help. This README describes the SDK's current API contract.
|
|
11
|
+
Report SDK bugs in [this repository](https://github.com/LiteraryUniverse/sdk-typescript/issues).
|
|
12
|
+
|
|
13
|
+
The client uses the deployment's `/graphql` endpoint. The core client has no runtime dependencies and exports ESM and CommonJS builds. Local image preparation uses the optional Sharp dependency through the `/images` entry point. Node 22 or later and Bun are targets; see CI and local verification for tested versions. `/graphql` sends no CORS headers, so code running on another origin, including an Obsidian plugin, must pass a `fetch` that is not subject to CORS, for example one built on Obsidian's `requestUrl`.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
The source is MIT licensed. The package is still marked private and has not been
|
|
18
|
+
released to npm. Build a tarball from this repository with Node 22 or later:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
git clone https://github.com/LiteraryUniverse/sdk-typescript.git
|
|
22
|
+
cd sdk-typescript
|
|
23
|
+
npm ci
|
|
24
|
+
npm pack
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Install that tarball in your application:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
npm install /path/to/sdk-typescript/literary-universe-sdk-0.1.0.tgz
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The package includes its schema, generated types and image policy. Building or
|
|
34
|
+
packing it does not require the Literary Universe monorepo. Git dependencies
|
|
35
|
+
also build through the package's `prepare` script.
|
|
36
|
+
|
|
37
|
+
## Quickstart
|
|
38
|
+
|
|
39
|
+
Create a personal API key in your Literary Universe account and grant only the
|
|
40
|
+
scopes your integration needs. The read example below needs `story:read`.
|
|
41
|
+
Provide the raw key through `LU_TOKEN` or your host application's secret store.
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
import { LiteraryUniverseClient, LiteraryUniverseApiError } from '@literary-universe/sdk'
|
|
45
|
+
|
|
46
|
+
const client = new LiteraryUniverseClient({
|
|
47
|
+
baseUrl: 'https://literaryuniverse.com',
|
|
48
|
+
token: process.env.LU_TOKEN!,
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
const identity = await client.identity()
|
|
52
|
+
const page = await client.stories({ first: 25 })
|
|
53
|
+
const story = page.nodes[0]
|
|
54
|
+
if (story) {
|
|
55
|
+
const chapters = await client.chapters({ storyId: story.id })
|
|
56
|
+
const chapter = chapters.nodes.find((chapter) => chapter.hasDraft)
|
|
57
|
+
if (chapter) {
|
|
58
|
+
const draft = await client.draft({ id: chapter.id })
|
|
59
|
+
console.log(draft)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
await client.story({ id: 'another-story-id' })
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error instanceof LiteraryUniverseApiError) {
|
|
67
|
+
console.error(error.code, error.requestId)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`baseUrl` identifies the deployment, including any mount prefix. Use the raw API token without `Bearer`. Cookies are omitted. Redirects are not followed and fail with `REDIRECTED`, so use the final URL: `https://www.literaryuniverse.com` redirects to `https://literaryuniverse.com`. HTTPS is required except on loopback addresses; a private HTTP deployment can explicitly set `allowInsecureHttp: true`. Token prefixes describe generation conditions and do not create an isolated database or sandbox.
|
|
73
|
+
|
|
74
|
+
## Supported reads
|
|
75
|
+
|
|
76
|
+
| Method | Scope | Result |
|
|
77
|
+
| --- | --- | --- |
|
|
78
|
+
| `identity()` | Any valid credential | API version, deployment label/URL, credential identity, granted scopes/restrictions and limits |
|
|
79
|
+
| `profile()` | `user:read` | Your user ID and optional username |
|
|
80
|
+
| `universes({first, after})` | `universe:read` | Paginated author/team universe headers |
|
|
81
|
+
| `universe({id})` | `universe:read` | Universe metadata and its translations, each with its `revision` |
|
|
82
|
+
| `stories({first, after})` | `story:read` | Paginated author/team story headers |
|
|
83
|
+
| `story({id})` | `story:read` | Story metadata and author notes |
|
|
84
|
+
| `chapters({storyId, language, first, after})` | `story:read` | Chapter headers without bodies |
|
|
85
|
+
| `draft({id, language})` | `story:read` | Stored working draft, including JSON, HTML/text/legacy representations and notes/counters |
|
|
86
|
+
|
|
87
|
+
Read access requires the person's current `draft.read` capability on the work or inherited universe. Personal credentials use current organization roles, including read-only view-all; removing a role affects subsequent requests. Organization-owned catalog credentials remain guests and cannot use author reads. Fan fiction is readable by its author and that story's own team; the team of the universe it is set in does not inherit it.
|
|
88
|
+
|
|
89
|
+
Draft language defaults to the chapter's original language. An explicit translation returns that stored edition; a missing edition or unavailable permission returns `NOT_FOUND`. Draft JSON preserves editor nodes and marks without conversion. Titles, descriptions and `html` are returned as the app displays them, with the stored entity encoding removed. `text` and `markdown` are returned as stored, where a literal `<` or `>` is `<` or `>`. `updatedAt` is existing metadata, not an atomic write-precondition version. Draft reads return a server version. Versioned content saves, validation, recovery, chapter creation, publication, and universe translations are available. Encyclopedia editing is later work.
|
|
90
|
+
|
|
91
|
+
Chapter headers include `hasDraft` for the requested edition. When a translation has not been created, its header retains the source title as a label, has `hasDraft: false`, and does not inherit the original's publication timestamp.
|
|
92
|
+
|
|
93
|
+
Lists default to 25 rows and accept 1–100. Follow `pageInfo.endCursor` while `hasNextPage` is true. Cursors are bound to the catalogue, credential restrictions and filters. They are ordered by stable IDs; chapter sequence is provided separately for writing order. Start a new traversal when changing credentials or catalogue inputs. Lists are live reads, not a database snapshot.
|
|
94
|
+
|
|
95
|
+
## Universe translations
|
|
96
|
+
|
|
97
|
+
| Method | Scope | Result |
|
|
98
|
+
| --- | --- | --- |
|
|
99
|
+
| `createUniverseTranslation({universeId, language, input?})` | `universe:translate` or `universe:write` | `{created, translation}`; an already open language returns `created: false` and the stored translation |
|
|
100
|
+
| `updateUniverseTranslation({universeId, language, expectedRevision, input})` | `universe:translate` or `universe:write` | The saved translation with its new `revision` |
|
|
101
|
+
|
|
102
|
+
A translation is the universe's title and description in another language. Who may write one follows the workshop: the owner, an organization admin, a team member who edits the universe, or a translator of that language. Opening a language copies the original title and description unless `input` provides them, and opens the language for the universe's encyclopedia and universe blog as the workshop does. The original language is refused with `BAD_USER_INPUT`. Send plain text: the title holds up to 100 characters and the description up to 800. A `null` or omitted field stays as it is.
|
|
103
|
+
|
|
104
|
+
`expectedRevision` is the `revision` you read from `universe({id})`. Every change advances it, including saves in the browser workshop, which overwrite without a revision. When the translation is no longer at `expectedRevision` the update changes nothing and fails with `VERSION_CONFLICT`; the error's `currentRevision` says where it is now, so read it again and decide what to write. Translations saved before revisions existed are at revision 0.
|
|
105
|
+
|
|
106
|
+
Writes are never retried, whatever `maxRetries` says: a lost response to an applied update would come back from a retry as a conflict. A resource-restricted credential can write to the universes it selects.
|
|
107
|
+
|
|
108
|
+
## Resource restrictions
|
|
109
|
+
|
|
110
|
+
Restricted credentials can be issued through the existing authenticated browser method; the resource picker belongs to the later developer-settings milestone:
|
|
111
|
+
|
|
112
|
+
```js
|
|
113
|
+
await Meteor.callAsync('apiKeys.create', {
|
|
114
|
+
name: 'Obsidian reads',
|
|
115
|
+
scopes: ['story:read', 'universe:read'],
|
|
116
|
+
resourceRestrictions: { universeIds: ['SELECTED_UNIVERSE_ID'] },
|
|
117
|
+
})
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
The method returns the token once. Keep it in your local secret store; never write it into an Obsidian vault or commit it. Existing expiry choices/default remain unchanged; the method still supports omitted expiry.
|
|
121
|
+
|
|
122
|
+
A selected universe covers its current and future descendant stories/chapters for these reads. A selected story covers itself and its chapters, without granting its parent universe. Containment comes from stored data and is checked again after moves. Selections supplement scopes and current user rights. Each category accepts at most 100 IDs; empty/malformed selections and inaccessible resources are rejected during issuance.
|
|
123
|
+
|
|
124
|
+
Restricted credentials are denied on legacy GraphQL operations and HTTP text exports that do not enforce these boundaries. Supported draft and universe-translation mutations enforce their stored resource boundaries. Protected media and AI remain session-only. Named SDK operations are client conveniences; server authorization applies to the GraphQL fields themselves.
|
|
125
|
+
|
|
126
|
+
## Errors and limits
|
|
127
|
+
|
|
128
|
+
`LiteraryUniverseApiError` provides `code`, a safe message, optional `requestId`, HTTP `status`, `retryAfterSeconds`, and `currentRevision` with `VERSION_CONFLICT`. Partial GraphQL data is rejected whenever the response contains errors. Missing and inaccessible resources both return `NOT_FOUND`. Common server codes include `UNAUTHENTICATED`, `FORBIDDEN`, `BAD_USER_INPUT`, `GRAPHQL_VALIDATION_FAILED`, `NOT_FOUND`, `VERSION_CONFLICT`, `PAYLOAD_TOO_LARGE`, and `INTERNAL_SERVER_ERROR`. Client/transport codes include `INVALID_CONFIGURATION`, `INVALID_RESPONSE`, `REDIRECTED`, `NETWORK_ERROR`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`, `TIMEOUT` and `CANCELLED`. An HTTP failure without a GraphQL error, such as a 404 from a wrong mount prefix, is `INVALID_RESPONSE`.
|
|
129
|
+
|
|
130
|
+
Requests retain the 1 MiB JSON ceiling. A draft pull is limited to 8 MiB; requests containing author operations have a 16 MiB response ceiling. The SDK also stops reading at 16 MiB. IP/batch protection remains. Deployed API-key traffic also consumes atomic per-key and owner budgets shared across instances. GraphQL development skips limits except in E2E mode; image transfers always consume shared credential quotas. Top-level aliases are charged as operations; a single query is limited to 20 roots.
|
|
131
|
+
|
|
132
|
+
Timeout defaults to 30 seconds for the entire request, including retries; valid values are 1–120,000 milliseconds. Pass `{signal, timeoutMs}` as the final method argument to cancel or override it. Retries default to zero and can be configured with `maxRetries: 1` or `2` for network failures and transparent HTTP 429/503 responses. Authentication/permission failures are never retried. Retry-After waits above ten seconds return the throttle error to the caller.
|
|
133
|
+
|
|
134
|
+
## Development and verification
|
|
135
|
+
|
|
136
|
+
```sh
|
|
137
|
+
npm ci
|
|
138
|
+
npm run generate
|
|
139
|
+
npm run check:generated
|
|
140
|
+
npm run typecheck
|
|
141
|
+
npm test
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`operations.graphql` is validated against the package-local `schema.graphql` artifact. LU CI checks that export against the app contract. Operation types/documents are generated from the supported server contract. When changing the server contract in the monorepo, regenerate `app/graphql.schema.json`, run `node app/scripts/exportSdkSchema.mjs`, then run `npm run generate --prefix sdk`. Commit the updated schema and generated files in this repository before advancing the monorepo submodule pointer. Generation/build/pack work without a sibling app. No generated runtime code depends on Meteor, Mongo, React or GraphQL libraries.
|
|
145
|
+
|
|
146
|
+
Live acceptance tests belong to the [Literary Universe monorepo](https://github.com/StorytellerCZ/Literary-Universe). With its `sdk` submodule initialized, start the app with tracked `settings.ci.json`, `ENABLE_E2E=1`, its own `.meteor/e2e` build and an isolated local Mongo replica-set database ending in `_test`. Draft and recovery records commit together in a transaction. Set `LU_API_TEST_MONGO_URL` and optionally `LU_API_TEST_BASE_URL`, then run `node --experimental-strip-types app/scripts/testApiReadContract.mjs` from the monorepo root. It issues credentials through real DDP methods, installs the tarball into a clean Node consumer, checks GraphQL/HTTP boundaries, and removes only its own credentials/fixtures and temporary files. The test fixture provisioner uses the app's Mongo dependency; the external consumer imports only Node built-ins and this packed SDK.
|
|
147
|
+
|
|
148
|
+
## Versioned draft writes
|
|
149
|
+
|
|
150
|
+
Use story:read and story:write to validate, save and consume the returned draft.
|
|
151
|
+
validateDraft accepts the same input as saveDraft, runs current permissions,
|
|
152
|
+
version and content checks, and returns warnings without changing content.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
const draft = await client.draft({ id: chapterId })
|
|
156
|
+
const input = { id: chapterId, language: draft.language, expectedVersion: draft.version,
|
|
157
|
+
operationId: crypto.randomUUID(), content: changedTiptapJson }
|
|
158
|
+
await client.validateDraft(input)
|
|
159
|
+
const saved = await client.saveDraft(input)
|
|
160
|
+
const before = await client.draftRecovery({ id: chapterId, recoveryId: saved.recoveryId })
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Retry an interrupted save with the same input and operation ID. A reused ID with
|
|
164
|
+
changed input yields IDEMPOTENCY_CONFLICT; a changed draft yields VERSION_CONFLICT.
|
|
165
|
+
The mutation changes body representations/counters only. Titles, notes, financial
|
|
166
|
+
settings and publication state are preserved. Supported browser nodes share one
|
|
167
|
+
schema; unsupported nodes become readable fallback with structured warnings.
|
|
168
|
+
The previous draft and saved response remain in a private recovery record for
|
|
169
|
+
30 days, after which MongoDB's TTL cleanup removes them. Replay saves within that
|
|
170
|
+
window. An expired retry may return VERSION_CONFLICT; pull the current draft and
|
|
171
|
+
reconcile it before starting a new operation. Creation and publication receipts
|
|
172
|
+
do not expire with draft recovery.
|
|
173
|
+
|
|
174
|
+
The version covers the whole chapter, including its translations. A translation
|
|
175
|
+
body save can therefore conflict with an original-language edit. Title-only and
|
|
176
|
+
settings-only edits do not advance it.
|
|
177
|
+
|
|
178
|
+
The initial write ceiling is 900,000 serialized UTF-8 bytes. In deployed builds,
|
|
179
|
+
set server settings authorApi.draftWritesEnabled to true. Optional
|
|
180
|
+
authorApi.allowedUserIds limits rollout to selected accounts. Development builds
|
|
181
|
+
allow it by default; setting draftWritesEnabled false disables it there too.
|
|
182
|
+
Production publication also requires authorApi.publicationEnabled to be true.
|
|
183
|
+
|
|
184
|
+
## Chapter lifecycle
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
const created = await client.createChapter({ storyId, operationId: crypto.randomUUID(),
|
|
188
|
+
title: 'New chapter', content: tiptapJson })
|
|
189
|
+
const released = await client.publishChapter({ id: created.id, expectedVersion: created.version,
|
|
190
|
+
operationId: crypto.randomUUID(), publishAt: '2027-01-01T12:00:00Z' })
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
createChapter requires story:write, appends in LU's chapter order, and returns
|
|
194
|
+
its ID/version, localized title and content warnings. Omitted content creates
|
|
195
|
+
an empty draft. It preserves story commercial settings and uses the normal
|
|
196
|
+
chapter defaults; isAIGenerated can be supplied explicitly. It does not publish.
|
|
197
|
+
|
|
198
|
+
publishChapter requires story:publish, separately issued by LU. READERS is the
|
|
199
|
+
default audience; BETA creates a private revision without changing reader release
|
|
200
|
+
dates. Existing translations can be selected by language. Missing publishAt means
|
|
201
|
+
now; an explicit timezone-bearing timestamp schedules that revision. Account/work
|
|
202
|
+
publication restrictions and course rules apply. A new Tiptap document is required
|
|
203
|
+
for canonical publication; save legacy drafts into that format first.
|
|
204
|
+
|
|
205
|
+
The matching draft, revision, listing changes, retry result and sjobs notification
|
|
206
|
+
jobs commit atomically. Publishing advances the draft version. publishedAt is the
|
|
207
|
+
revision's release time; chapterPublishedAt retains or advances the chapter's first
|
|
208
|
+
release time, matching LU's existing earlier-release behavior. The first original
|
|
209
|
+
chapter publishes its story; moving its scheduled release earlier also moves an
|
|
210
|
+
existing later story opening earlier. Universe visibility remains a separate LU operation;
|
|
211
|
+
a selected story does not implicitly grant publication of its parent universe.
|
|
212
|
+
|
|
213
|
+
Operation IDs are scoped to the credential owner and operation target, rather
|
|
214
|
+
than being globally unique. Saves use the chapter and resolved language; creation
|
|
215
|
+
uses the story; publication uses the chapter; image uploads use the purpose and
|
|
216
|
+
target. Reusing an ID for another target or action starts a separate operation.
|
|
217
|
+
Within that scope, changed input returns IDEMPOTENCY_CONFLICT. Use a fresh random
|
|
218
|
+
ID for each new operation and keep it unchanged for retries. Key rotation does
|
|
219
|
+
not create duplicates. Replays return the committed result after
|
|
220
|
+
current authorization, before new-write constraints. Creation metadata remains
|
|
221
|
+
durable after later deletion; retrying returns the original ID and does not recreate
|
|
222
|
+
the chapter. Recovery bodies are removed when the corresponding chapter is erased.
|
|
223
|
+
|
|
224
|
+
Browser creation/deletion use the shared transaction boundary. Browser/offline draft
|
|
225
|
+
saves retain their current UX; counters are recalculated from persisted editions.
|
|
226
|
+
API saves record challenge progress from that same transaction's word count, so
|
|
227
|
+
retrying an old save cannot move newer progress into an earlier day.
|
|
228
|
+
The legacy browser revision adapter remains separate from this API publication path.
|
|
229
|
+
|
|
230
|
+
Credential quotas default to 300 operations/minute/key for regular/staff keys,
|
|
231
|
+
600 for premium keys, and three times the respective limit across the owner.
|
|
232
|
+
Server settings apiRateLimits.user and apiRateLimits.premium can tune the finite
|
|
233
|
+
key limit; owner limits scale with it. A failed shared store returns a retryable
|
|
234
|
+
503. Rate diagnostics include Retry-After, remaining and reset headers.
|
|
235
|
+
|
|
236
|
+
Use the /project entry point for managed filesystem projects, or supply a
|
|
237
|
+
credential provider when the host owns storage/rotation:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
const client = new LiteraryUniverseClient({ baseUrl,
|
|
241
|
+
credentials: async signal => ({ kind: 'api-key', token: await getCurrentKey(signal) }),
|
|
242
|
+
clientName: 'my-integration/0.1' })
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
The provider is covered by the request deadline. API keys remain the only
|
|
246
|
+
supported credential kind; the provider interface leaves room for deliberate
|
|
247
|
+
OAuth support later. Client names are bounded reported metadata for server audit.
|
|
248
|
+
There are no automatic telemetry providers or exporters.
|
|
249
|
+
|
|
250
|
+
## Images
|
|
251
|
+
|
|
252
|
+
Install the existing supported image engine with `npm install sharp@0.35.5` in a
|
|
253
|
+
consumer that uses /images. The CLI installs it automatically. Core API calls and
|
|
254
|
+
policy reads do not load Sharp.
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
import { readFile } from 'node:fs/promises'
|
|
258
|
+
import { prepareImage } from '@literary-universe/sdk/images'
|
|
259
|
+
|
|
260
|
+
const policy = await client.imagePolicy()
|
|
261
|
+
const image = await prepareImage(await readFile('scene.png'), 'chapter-image', { policy })
|
|
262
|
+
const asset = await client.uploadImage({ ...image, targetId: chapterId,
|
|
263
|
+
operationId: crypto.randomUUID() })
|
|
264
|
+
|
|
265
|
+
const cover = await prepareImage(await readFile('cover.png'), 'story-cover', { policy })
|
|
266
|
+
await client.setCover({ kind: 'story', id: storyId, bytes: cover.bytes, type: cover.type })
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Preparation runs locally in a killable subprocess. It accepts single-frame raster
|
|
270
|
+
images, corrects EXIF orientation, strips metadata, preserves transparency, and
|
|
271
|
+
resizes/compresses to the selected purpose's finite limits. A forced JPEG output
|
|
272
|
+
is rejected when it would discard transparency. SVG, document and multi-frame
|
|
273
|
+
inputs require an explicit raster/single-frame export. Originals remain untouched;
|
|
274
|
+
no remote references are fetched. A crop must be explicit: `{crop: {left, top,
|
|
275
|
+
width, height}}` uses pixels after orientation. A wrong enforced ratio returns
|
|
276
|
+
CROP_REQUIRED. Recommended cover dimensions do not impose a resize.
|
|
277
|
+
|
|
278
|
+
The versioned policy is packaged for offline use and available from imagePolicy.
|
|
279
|
+
LU and the SDK consume exported copies of the same policy data. The initial
|
|
280
|
+
processing bounds are 50 MiB source bytes, 40 million source pixels, 16 million
|
|
281
|
+
output pixels and ten seconds, including metadata parsing. Smaller server limits
|
|
282
|
+
apply; larger remote limits never raise the SDK's local processing ceilings.
|
|
283
|
+
Story/universe covers, chapter and encyclopedia images, blog images and headers
|
|
284
|
+
have a 5 MiB upload ceiling; blog logos have 2 MiB. Covers enforce 2:3 and 1:1;
|
|
285
|
+
blog post images use 16:9 with a consistent 1200×675 recommendation.
|
|
286
|
+
|
|
287
|
+
uploadImage creates a public asset in LU's existing ImagesCollection/storage. It
|
|
288
|
+
returns an ID, URL, digest, size and dimensions. It does not attach, replace or
|
|
289
|
+
publish content. Use story:write for chapter images, universe:write for
|
|
290
|
+
encyclopedia illustrations, and blog:write for blog assets. It refuses cover
|
|
291
|
+
purposes: setCover replaces a story's (story:write) or universe's
|
|
292
|
+
(universe:write) cover through `PUT /api/{stories,universes}/:id/cover`, which
|
|
293
|
+
crops to the cover shape and stores WebP. It takes no operation ID; retrying sets
|
|
294
|
+
the same cover again. Prepare with the cover purposes to stay within 5 MiB.
|
|
295
|
+
Current target capabilities, course rules, plan restrictions and selected-resource
|
|
296
|
+
boundaries still apply. Chapter uploads target a chapter, encyclopedia uploads
|
|
297
|
+
an entry, and blog purposes target their blog. Chapter
|
|
298
|
+
images currently target the original edition; translation-specific asset writes
|
|
299
|
+
remain to add. Restricted story/universe keys cannot target blogs. Universe/blog
|
|
300
|
+
write scopes currently enable asset creation; broader editing contracts are later.
|
|
301
|
+
|
|
302
|
+
Binary transfers use /api/author/images, bypassing the GraphQL JSON ceiling. LU
|
|
303
|
+
checks the actual format, full decode, bytes, geometry and ratio. Requests cost ten
|
|
304
|
+
ordinary operations against shared key/owner quotas. Concurrent transfers are
|
|
305
|
+
bounded to one per key, three per owner and eight per deployment, with four
|
|
306
|
+
decoders per server process. Body transfer has a twenty-second deadline; decoding
|
|
307
|
+
has a killable ten-second deadline. Unavailable enforcement/storage fails closed.
|
|
308
|
+
Transfer and intent leases renew while work is active; renewal calls are bounded
|
|
309
|
+
to ten seconds and the final asset/result transaction to twenty-five seconds.
|
|
310
|
+
Production uses the existing authorApi.draftWritesEnabled/allowedUserIds rollout.
|
|
311
|
+
|
|
312
|
+
Keep the prepared bytes and operation ID for retry. Changed input yields
|
|
313
|
+
IDEMPOTENCY_CONFLICT; committed replay returns the original asset after current
|
|
314
|
+
authorization, including after credential rotation or a smaller current purpose
|
|
315
|
+
limit, within the fixed 5 MiB transport ceiling. New input using an old policy
|
|
316
|
+
returns POLICY_CHANGED. An ambiguous storage/commit failure may require waiting
|
|
317
|
+
for its 90-second lease; retry checks the deterministic storage key's digest
|
|
318
|
+
before creating bytes again. Safe API/client attribution uses LU's existing audit
|
|
319
|
+
collection. Storage remains public; protected comic/audio files use other contracts.
|
|
320
|
+
|
|
321
|
+
For live image checks, configure an isolated local S3-compatible test endpoint in
|
|
322
|
+
the test server's Backblaze settings, then run `node app/scripts/testApiImageContract.mjs` from the monorepo root with the same
|
|
323
|
+
local _test database variables as test:integration. Real Backblaze verification
|
|
324
|
+
remains a separate rollout check.
|
|
325
|
+
|
|
326
|
+
Platform CI runs the package checks on Windows and macOS, including both Intel
|
|
327
|
+
and Apple Silicon Macs. These checks cover extracted builds, packed consumers,
|
|
328
|
+
image preparation/cancellation and CLI credential storage. Local project and
|
|
329
|
+
source JSON files accept UTF-8 BOM and CRLF; chapter filenames must be distinct
|
|
330
|
+
ignoring case so moving a project between these filesystems cannot overwrite a
|
|
331
|
+
different chapter.
|
|
332
|
+
|
|
333
|
+
The monorepo provides a local storage fixture: run
|
|
334
|
+
`node app/scripts/serveApiImageTestStorage.mjs /tmp/lu-image-settings.json`, start
|
|
335
|
+
the isolated Meteor test server with that settings file, and stop both owned
|
|
336
|
+
processes after verification. The fixture uses synthetic credentials and checks
|
|
337
|
+
real S3 transport without contacting Backblaze. It is not a production server.
|