Amir T. 판매

Official JavaScript client for Sanity's Content Lake. Supports querying, mutations, real-time listeners, asset uploads, and perspectives across Node.js, browsers, Bun, Deno, and Edge Runtime.
This block packages the full source of @sanity/client@7.21.0 — Sanity's official JavaScript/TypeScript Content Lake client — directly into your project. It targets Node.js, Bun, Deno, Edge Runtime, and modern browsers. The typical buyer is a TypeScript backend or full-stack developer who needs fine-grained control over the client source, wants to fork behaviour, or is vendoring the client into a monorepo.
source/SanityClient.ts — Core SanityClient and ObservableSanityClient class definitionssource/config.ts — Config initialization, defaults, and validation logicsource/defineCreateClient.ts — Factory that wires middleware + client class into createClient / requestersource/defineDeprecatedCreateClient.ts — Compatibility shim for the legacy default exportsource/generateHelpUrl.ts — Generates documentation URLs for error messagessource/index.ts — Node.js entry point; re-exports everything publicsource/index.browser.ts — Browser entry point with browser-specific middlewaresource/media-library.ts — Media library sub-entry pointsource/types.ts — All public and internal TypeScript typessource/validators.ts — Runtime config and input validatorssource/warnings.ts — Console warning helperssource/agent/ — Agent Actions client (generate, patch, prompt, transform, translate)source/assets/ — Asset upload client (AssetsClient)source/csm/ — Content Source Maps utilities (edit URLs, path resolution, draft utils)source/data/ — Core data methods: fetch, listen, live, patch, transaction, eventsourcesource/datasets/ — Dataset management clientsource/http/ — HTTP middleware for Node and browser, error types, request buildersource/mediaLibrary/ — Media Library video clientsource/projects/ — Projects management clientsource/releases/ — Releases client and helpers격리된 샌드박스를 띄워 서버에서 바로 실행하세요 — 로컬 설정 불필요.
이 버전에 대한 Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
파이프라인 avcp-2026-08-04.1 · SHA-256 5618079bd0e31fbb…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
검토일 2026년 8월 4일
이 제품을 AI IDE, 웹 빌더 또는 클라우드 IDE로 바로 가져오세요.
Tetrees를 호환 AI IDE에 연결해 보유 제품을 불러오고, 판매자 업로드 권한을 노출하지 않은 채 검증된 ZIP을 받으세요.
아직 리뷰가 없습니다.
토론을 불러오는 중…
source/stega/ — Steganography encoding/decoding for Visual Editingsource/users/ — Users clientsource/util/ — Internal utilities: codeFrame, createVersionId, defaults, pick, once, getSelectionnpm install get-it rxjs nanoid @sanity/eventsource
No native modules, no pod install, no prebuild steps required. For Edge Runtime or Deno, use the index.browser.ts entry (or the published CDN URL) rather than index.ts which pulls in Node-specific middleware.
Copy the source/ directory into your project, e.g. src/sanity-client/.
Update tsconfig.json to include the source and enable the required compiler options:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"paths": {
"@sanity/client": ["./src/sanity-client/index.ts"],
"@sanity/client/csm": ["./src/sanity-client/csm/index.ts"],
"@sanity/client/stega": ["./src/sanity-client/stega/index.ts"]
}
}
}
SANITY_PROJECT_ID=your-project-id
SANITY_DATASET=production
SANITY_API_TOKEN=sk...
// src/lib/sanity.ts
import {createClient} from './sanity-client/index.ts'
export const client = createClient({
projectId: process.env.SANITY_PROJECT_ID!,
dataset: process.env.SANITY_DATASET!,
apiVersion: '2025-02-06', // hard-code; never use new Date()
useCdn: true,
token: process.env.SANITY_API_TOKEN,
})
import {createClient} from './sanity-client/index.ts'
const client = createClient(config: ClientConfig): SanityClient
Primary factory function. Accepts a ClientConfig object and returns a fully initialized SanityClient. Use this as the single entry point for all Sanity API interactions.
import {SanityClient} from './sanity-client/index.ts'
class SanityClient {
fetch<R>(query: string, params?: QueryParams, options?: QueryOptions): Promise<R>
create<R extends SanityDocumentStub>(doc: R, options?: BaseMutationOptions): Promise<SanityDocument<R>>
patch(documentId: PatchSelection): Patch
delete(selection: MutationSelection, options?: BaseMutationOptions): Promise<SingleMutationResult>
transaction(): Transaction
listen<R>(query: string, params?: QueryParams): Observable<MutationEvent<R>>
config(newConfig?: Partial<ClientConfig>): InitializedClientConfig | this
withConfig(newConfig: Partial<ClientConfig>): SanityClient
datasets: DatasetsClient
projects: ProjectsClient
assets: AssetsClient
users: UsersClient
releases: ReleasesClient
agent: AgentActionsClient
}
The main client class. Use fetch for GROQ queries, patch/create/delete for mutations, listen for real-time updates, and withConfig to derive a scoped client with different settings.
import {requester} from './sanity-client/index.ts'
const requester: Requester
The underlying get-it requester instance used by the client. Use this when you need to make raw HTTP requests to Sanity APIs without the full client abstraction, or when wiring custom middleware.
import {stegaClean} from './sanity-client/stega/index.ts'
function stegaClean<T>(result: T): T
Strips steganography-encoded data from query results. Use before rendering user-visible content or sending data to third-party services that must not receive encoded payloads.
Query all published posts and decode the result type. This is the baseline pattern for read-only data fetching.
import {createClient} from './sanity-client/index.ts'
const client = createClient({
projectId: 'abc123',
dataset: 'production',
apiVersion: '2025-02-06',
useCdn: true,
perspective: 'published',
})
interface Post {
_id: string
_type: 'post'
title: string
slug: {current: string}
}
async function getPosts(): Promise<Post[]> {
return client.fetch<Post[]>('*[_type == "post"]{_id, _type, title, slug}')
}
const posts = await getPosts()
console.log(posts)
Atomically create a document and immediately update a related record inside a single transaction.
import {createClient} from './sanity-client/index.ts'
const client = createClient({
projectId: 'abc123',
dataset: 'production',
apiVersion: '2025-02-06',
useCdn: false,
token: process.env.SANITY_API_TOKEN,
})
async function publishArticle(draft: {_type: string; title: string; body: string}) {
const result = await client
.transaction()
.create({_type: draft._type, title: draft.title, body: draft.body})
.patch('site-settings', (p) => p.setIfMissing({lastPublished: null}).set({lastPublished: new Date().toISOString()}))
.commit()
return result
}
Subscribe to live mutations on a document type. Use RxJS operators since listen returns an Observable.
import {createClient} from './sanity-client/index.ts'
import {filter, map} from 'rxjs/operators'
const client = createClient({
projectId: 'abc123',
dataset: 'production',
apiVersion: '2025-02-06',
useCdn: false,
token: process.env.SANITY_API_TOKEN,
})
const subscription = client
.listen('*[_type == "comment"]', {}, {includeResult: true})
.pipe(
filter((event) => event.type === 'mutation'),
map((event) => event.result),
)
.subscribe((comment) => {
console.log('New/updated comment:', comment)
})
// Clean up when done
// subscription.unsubscribe()
Fetch with Content Source Maps enabled, pass encoded data to the Visual Editing layer, and clean before external use.
import {createClient} from './sanity-client/index.ts'
import {stegaClean} from './sanity-client/stega/index.ts'
const client = createClient({
projectId: 'abc123',
dataset: 'production',
apiVersion: '2025-02-06',
useCdn: true,
stega: {enabled: true, studioUrl: 'https://your-studio.sanity.studio'},
})
const data = await client.fetch('*[_type == "page"][0]{title, body}')
// Pass `data` to your visual editing overlay as-is.
// Before sending to analytics or external APIs, strip encoding:
const cleanData = stegaClean(data)
console.log(cleanData)
index.ts — Node.js public entry; calls defineCreateClientExports with Node middleware, exports createClient, requester, and all types.index.browser.ts — Browser public entry; same shape as index.ts but uses browserMiddleware.SanityClient.ts — Implements SanityClient and ObservableSanityClient with all query, mutation, and sub-client methods.config.ts — initConfig validates and merges ClientConfig into InitializedClientConfig; defaultConfig holds baseline values.defineCreateClient.ts — Exports the createClient factory and ClientConfig type; parameterized over client class and config.defineDeprecatedCreateClient.ts — Wraps createClient for the legacy default export pattern.types.ts — Canonical location for all public TypeScript types: ClientConfig, SanityDocument, QueryOptions, ClientPerspective, etc.validators.ts — Runtime checks on project IDs, dataset names, and config fields.warnings.ts — Centralized console.warn wrappers for deprecation notices.generateHelpUrl.ts — Builds https://www.sanity.io/help/... URLs embedded in thrown errors.media-library.ts — Dedicated entry point re-exporting the media library client.agent/ — AgentActionsClient and per-action files (generate, patch, prompt, transform, translate) for Sanity Agent Actions API.assets/ — AssetsClient handling file and image uploads.csm/ — Content Source Maps: applySourceDocuments, resolveEditInfo, resolveEditUrl, draftUtils, jsonPath, studioPath, walkMap.data/ — Core data layer: dataMethods (fetch, getDocument), listen, live, patch, transaction, eventsource, encodeQueryString.datasets/ — DatasetsClient with CRUD for datasets.http/ — browserMiddleware, nodeMiddleware, errors, request, requestOptions — the HTTP abstraction layer.mediaLibrary/ — MediaLibraryVideoClient for media library video operations.projects/ — ProjectsClient for project-level API operations.releases/ — ReleasesClient and createRelease helper for content releases.stega/ — Steganography encoding (stegaEncodeSourceMap, encodeIntoResult), cleaning (stegaClean, vercelStegaCleanAll), and stega-aware client exports.users/ — UsersClient for fetching user information.util/ — Internal helpers: codeFrame, createVersionId, defaults, getSelection, isRecord, once, pick.apiVersion: Never use new Date() for apiVersion; it will break your app when the date advances past an API boundary. Pin a fixed string like '2025-02-06'.index.ts in an Edge Runtime pulls in nodeMiddleware which references Node.js built-ins. Use index.browser.ts or alias the package to the browser entry in your bundler config.perspective default changed: As of v2025-02-19, the default perspective is published not raw. Queries that previously returned draft documents may silently return fewer results — set perspective: 'raw' explicitly if you need the old behaviour.token for mutations: create, patch, delete, and listening to private datasets all require a token with write/read permissions. Requests silently return 401 if omitted.rxjs version mismatch: The source imports from rxjs directly. Ensure your project has rxjs@^7 installed; mixing v6 and v7 in a monorepo will cause runtime errors.tsconfig moduleResolution: This source uses modern ESM imports with explicit .ts extensions. Set moduleResolution to NodeNext or Bundler; Node (classic) resolution will fail to resolve sub-path imports like @sanity/client/csm.I have vendored the source of @sanity/client@7.21.0 into `src/sanity-client/`.
There is a USAGE.md file at the root of this block that documents all public
exports, working code examples, setup steps, and common pitfalls.
Please read USAGE.md and the files under `src/sanity-client/` and then:
1. Install the required dependencies listed in USAGE.md (get-it, rxjs, nanoid,
@sanity/eventsource) into my project.
2. Create a shared client instance at `src/lib/sanity.ts` using `createClient`
from `src/sanity-client/index.ts`, reading credentials from environment
variables SANITY_PROJECT_ID, SANITY_DATASET, and SANITY_API_TOKEN.
3. Update `tsconfig.json` so that imports of `@sanity/client` and
`@sanity/client/csm` resolve to the vendored source via path aliases.
4. Integrate the client into my existing project by:
[DESCRIBE YOUR USE CASE HERE — e.g. "adding a /api/posts route in my
Express app that fetches all published posts" or "replacing my current
fetch calls with typed GROQ queries"]
5. Add a real-time listener using `client.listen()` for [DESCRIBE DOCUMENT
TYPE] and wire it to [DESCRIBE YOUR STATE/HANDLER].
6. Show me how to clean stega-encoded results with `stegaClean` before I
pass data to [DESCRIBE EXTERNAL SERVICE].
Follow the patterns in USAGE.md exactly. Do not invent any API methods not
documented there.
The upstream project is licensed under the MIT License — see source/LICENSE if present, or refer to the npm package page. This block is derived from @sanity/client@7.21.0 published by Sanity.io.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
전체 설치 가이드와 연동 프롬프트는 구매 후 열람할 수 있습니다.
CRM, ERP, Admin & Internal Tools
무료