@sanity/client 3.4.0-beta.esm.1 → 3.4.0-beta.esm.2

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/src/data/patch.js DELETED
@@ -1,124 +0,0 @@
1
- const assign = require('object-assign')
2
- const getSelection = require('../util/getSelection')
3
- const validate = require('../validators')
4
- const validateObject = validate.validateObject
5
- const validateInsert = validate.validateInsert
6
-
7
- function Patch(selection, operations = {}, client = null) {
8
- this.selection = selection
9
- this.operations = assign({}, operations)
10
- this.client = client
11
- }
12
-
13
- assign(Patch.prototype, {
14
- clone() {
15
- return new Patch(this.selection, assign({}, this.operations), this.client)
16
- },
17
-
18
- set(props) {
19
- return this._assign('set', props)
20
- },
21
-
22
- diffMatchPatch(props) {
23
- validateObject('diffMatchPatch', props)
24
- return this._assign('diffMatchPatch', props)
25
- },
26
-
27
- unset(attrs) {
28
- if (!Array.isArray(attrs)) {
29
- throw new Error('unset(attrs) takes an array of attributes to unset, non-array given')
30
- }
31
-
32
- this.operations = assign({}, this.operations, {unset: attrs})
33
- return this
34
- },
35
-
36
- setIfMissing(props) {
37
- return this._assign('setIfMissing', props)
38
- },
39
-
40
- replace(props) {
41
- validateObject('replace', props)
42
- return this._set('set', {$: props}) // eslint-disable-line id-length
43
- },
44
-
45
- inc(props) {
46
- return this._assign('inc', props)
47
- },
48
-
49
- dec(props) {
50
- return this._assign('dec', props)
51
- },
52
-
53
- insert(at, selector, items) {
54
- validateInsert(at, selector, items)
55
- return this._assign('insert', {[at]: selector, items})
56
- },
57
-
58
- append(selector, items) {
59
- return this.insert('after', `${selector}[-1]`, items)
60
- },
61
-
62
- prepend(selector, items) {
63
- return this.insert('before', `${selector}[0]`, items)
64
- },
65
-
66
- splice(selector, start, deleteCount, items) {
67
- // Negative indexes doesn't mean the same in Sanity as they do in JS;
68
- // -1 means "actually at the end of the array", which allows inserting
69
- // at the end of the array without knowing its length. We therefore have
70
- // to substract negative indexes by one to match JS. If you want Sanity-
71
- // behaviour, just use `insert('replace', selector, items)` directly
72
- const delAll = typeof deleteCount === 'undefined' || deleteCount === -1
73
- const startIndex = start < 0 ? start - 1 : start
74
- const delCount = delAll ? -1 : Math.max(0, start + deleteCount)
75
- const delRange = startIndex < 0 && delCount >= 0 ? '' : delCount
76
- const rangeSelector = `${selector}[${startIndex}:${delRange}]`
77
- return this.insert('replace', rangeSelector, items || [])
78
- },
79
-
80
- ifRevisionId(rev) {
81
- this.operations.ifRevisionID = rev
82
- return this
83
- },
84
-
85
- serialize() {
86
- return assign(getSelection(this.selection), this.operations)
87
- },
88
-
89
- toJSON() {
90
- return this.serialize()
91
- },
92
-
93
- commit(options = {}) {
94
- if (!this.client) {
95
- throw new Error(
96
- 'No `client` passed to patch, either provide one or pass the ' +
97
- 'patch to a clients `mutate()` method'
98
- )
99
- }
100
-
101
- const returnFirst = typeof this.selection === 'string'
102
- const opts = assign({returnFirst, returnDocuments: true}, options)
103
- return this.client.mutate({patch: this.serialize()}, opts)
104
- },
105
-
106
- reset() {
107
- this.operations = {}
108
- return this
109
- },
110
-
111
- _set(op, props) {
112
- return this._assign(op, props, false)
113
- },
114
-
115
- _assign(op, props, merge = true) {
116
- validateObject(op, props)
117
- this.operations = assign({}, this.operations, {
118
- [op]: assign({}, (merge && this.operations[op]) || {}, props),
119
- })
120
- return this
121
- },
122
- })
123
-
124
- module.exports = Patch
@@ -1,106 +0,0 @@
1
- const assign = require('object-assign')
2
- const validators = require('../validators')
3
- const Patch = require('./patch')
4
-
5
- const defaultMutateOptions = {returnDocuments: false}
6
-
7
- function Transaction(operations = [], client, transactionId) {
8
- this.trxId = transactionId
9
- this.operations = operations
10
- this.client = client
11
- }
12
-
13
- assign(Transaction.prototype, {
14
- clone() {
15
- return new Transaction(this.operations.slice(0), this.client, this.trxId)
16
- },
17
-
18
- create(doc) {
19
- validators.validateObject('create', doc)
20
- return this._add({create: doc})
21
- },
22
-
23
- createIfNotExists(doc) {
24
- const op = 'createIfNotExists'
25
- validators.validateObject(op, doc)
26
- validators.requireDocumentId(op, doc)
27
- return this._add({[op]: doc})
28
- },
29
-
30
- createOrReplace(doc) {
31
- const op = 'createOrReplace'
32
- validators.validateObject(op, doc)
33
- validators.requireDocumentId(op, doc)
34
- return this._add({[op]: doc})
35
- },
36
-
37
- delete(documentId) {
38
- validators.validateDocumentId('delete', documentId)
39
- return this._add({delete: {id: documentId}})
40
- },
41
-
42
- patch(documentId, patchOps) {
43
- const isBuilder = typeof patchOps === 'function'
44
- const isPatch = documentId instanceof Patch
45
-
46
- // transaction.patch(client.patch('documentId').inc({visits: 1}))
47
- if (isPatch) {
48
- return this._add({patch: documentId.serialize()})
49
- }
50
-
51
- // patch => patch.inc({visits: 1}).set({foo: 'bar'})
52
- if (isBuilder) {
53
- const patch = patchOps(new Patch(documentId, {}, this.client))
54
- if (!(patch instanceof Patch)) {
55
- throw new Error('function passed to `patch()` must return the patch')
56
- }
57
-
58
- return this._add({patch: patch.serialize()})
59
- }
60
-
61
- return this._add({patch: assign({id: documentId}, patchOps)})
62
- },
63
-
64
- transactionId(id) {
65
- if (!id) {
66
- return this.trxId
67
- }
68
-
69
- this.trxId = id
70
- return this
71
- },
72
-
73
- serialize() {
74
- return this.operations.slice()
75
- },
76
-
77
- toJSON() {
78
- return this.serialize()
79
- },
80
-
81
- commit(options) {
82
- if (!this.client) {
83
- throw new Error(
84
- 'No `client` passed to transaction, either provide one or pass the ' +
85
- 'transaction to a clients `mutate()` method'
86
- )
87
- }
88
-
89
- return this.client.mutate(
90
- this.serialize(),
91
- assign({transactionId: this.trxId}, defaultMutateOptions, options || {})
92
- )
93
- },
94
-
95
- reset() {
96
- this.operations = []
97
- return this
98
- },
99
-
100
- _add(mut) {
101
- this.operations.push(mut)
102
- return this
103
- },
104
- })
105
-
106
- module.exports = Transaction
@@ -1,31 +0,0 @@
1
- const assign = require('object-assign')
2
- const validate = require('../validators')
3
-
4
- function DatasetsClient(client) {
5
- this.request = client.request.bind(client)
6
- }
7
-
8
- assign(DatasetsClient.prototype, {
9
- create(name, options) {
10
- return this._modify('PUT', name, options)
11
- },
12
-
13
- edit(name, options) {
14
- return this._modify('PATCH', name, options)
15
- },
16
-
17
- delete(name) {
18
- return this._modify('DELETE', name)
19
- },
20
-
21
- list() {
22
- return this.request({uri: '/datasets'})
23
- },
24
-
25
- _modify(method, name, body) {
26
- validate.dataset(name)
27
- return this.request({method, uri: `/datasets/${name}`, body})
28
- },
29
- })
30
-
31
- module.exports = DatasetsClient
@@ -1 +0,0 @@
1
- module.exports = []
@@ -1,57 +0,0 @@
1
- const makeError = require('make-error')
2
- const assign = require('object-assign')
3
-
4
- function ClientError(res) {
5
- const props = extractErrorProps(res)
6
- ClientError.super.call(this, props.message)
7
- assign(this, props)
8
- }
9
-
10
- function ServerError(res) {
11
- const props = extractErrorProps(res)
12
- ServerError.super.call(this, props.message)
13
- assign(this, props)
14
- }
15
-
16
- function extractErrorProps(res) {
17
- const body = res.body
18
- const props = {
19
- response: res,
20
- statusCode: res.statusCode,
21
- responseBody: stringifyBody(body, res),
22
- }
23
-
24
- // API/Boom style errors ({statusCode, error, message})
25
- if (body.error && body.message) {
26
- props.message = `${body.error} - ${body.message}`
27
- return props
28
- }
29
-
30
- // Query/database errors ({error: {description, other, arb, props}})
31
- if (body.error && body.error.description) {
32
- props.message = body.error.description
33
- props.details = body.error
34
- return props
35
- }
36
-
37
- // Other, more arbitrary errors
38
- props.message = body.error || body.message || httpErrorMessage(res)
39
- return props
40
- }
41
-
42
- function httpErrorMessage(res) {
43
- const statusMessage = res.statusMessage ? ` ${res.statusMessage}` : ''
44
- return `${res.method}-request to ${res.url} resulted in HTTP ${res.statusCode}${statusMessage}`
45
- }
46
-
47
- function stringifyBody(body, res) {
48
- const contentType = (res.headers['content-type'] || '').toLowerCase()
49
- const isJson = contentType.indexOf('application/json') !== -1
50
- return isJson ? JSON.stringify(body, null, 2) : body
51
- }
52
-
53
- makeError(ClientError)
54
- makeError(ServerError)
55
-
56
- exports.ClientError = ClientError
57
- exports.ServerError = ServerError
@@ -1,13 +0,0 @@
1
- const retry = require('get-it/lib-node/middleware/retry')
2
- const debug = require('get-it/lib-node/middleware/debug')
3
- const headers = require('get-it/lib-node/middleware/headers')
4
-
5
- const pkg = require('../../package.json')
6
-
7
- const middleware = [
8
- debug({verbose: true, namespace: 'sanity:client'}),
9
- headers({'User-Agent': `${pkg.name} ${pkg.version}`}),
10
- retry({maxRetries: 3}),
11
- ]
12
-
13
- module.exports = middleware
@@ -1,10 +0,0 @@
1
- module.exports = (params) => {
2
- const qs = []
3
- for (const key in params) {
4
- if (params.hasOwnProperty(key)) {
5
- qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
6
- }
7
- }
8
-
9
- return qs.length > 0 ? `?${qs.join('&')}` : ''
10
- }
@@ -1,54 +0,0 @@
1
- /* eslint-disable no-empty-function, no-process-env */
2
- const getIt = require('get-it')
3
- const assign = require('object-assign')
4
- const observable = require('get-it/lib/middleware/observable')
5
- const jsonRequest = require('get-it/lib/middleware/jsonRequest')
6
- const jsonResponse = require('get-it/lib/middleware/jsonResponse')
7
- const progress = require('get-it/lib/middleware/progress')
8
- const {Observable} = require('../util/observable')
9
- const {ClientError, ServerError} = require('./errors')
10
-
11
- const httpError = {
12
- onResponse: (res) => {
13
- if (res.statusCode >= 500) {
14
- throw new ServerError(res)
15
- } else if (res.statusCode >= 400) {
16
- throw new ClientError(res)
17
- }
18
-
19
- return res
20
- },
21
- }
22
-
23
- const printWarnings = {
24
- onResponse: (res) => {
25
- const warn = res.headers['x-sanity-warning']
26
- const warnings = Array.isArray(warn) ? warn : [warn]
27
- warnings.filter(Boolean).forEach((msg) => console.warn(msg)) // eslint-disable-line no-console
28
- return res
29
- },
30
- }
31
-
32
- // Environment-specific middleware.
33
- const envSpecific = require('./nodeMiddleware')
34
-
35
- const middleware = envSpecific.concat([
36
- printWarnings,
37
- jsonRequest(),
38
- jsonResponse(),
39
- progress(),
40
- httpError,
41
- observable({implementation: Observable}),
42
- ])
43
-
44
- const request = getIt(middleware)
45
-
46
- function httpRequest(options, requester = request) {
47
- return requester(assign({maxRedirects: 0}, options))
48
- }
49
-
50
- httpRequest.defaultRequester = request
51
- httpRequest.ClientError = ClientError
52
- httpRequest.ServerError = ServerError
53
-
54
- module.exports = httpRequest
@@ -1,31 +0,0 @@
1
- const assign = require('object-assign')
2
-
3
- const projectHeader = 'X-Sanity-Project-ID'
4
-
5
- module.exports = (config, overrides = {}) => {
6
- const headers = {}
7
-
8
- const token = overrides.token || config.token
9
- if (token) {
10
- headers.Authorization = `Bearer ${token}`
11
- }
12
-
13
- if (!overrides.useGlobalApi && !config.useProjectHostname && config.projectId) {
14
- headers[projectHeader] = config.projectId
15
- }
16
-
17
- const withCredentials = Boolean(
18
- typeof overrides.withCredentials === 'undefined'
19
- ? config.token || config.withCredentials
20
- : overrides.withCredentials
21
- )
22
-
23
- const timeout = typeof overrides.timeout === 'undefined' ? config.timeout : overrides.timeout
24
- return assign({}, overrides, {
25
- headers: assign({}, headers, overrides.headers || {}),
26
- timeout: typeof timeout === 'undefined' ? 5 * 60 * 1000 : timeout,
27
- proxy: overrides.proxy || config.proxy,
28
- json: true,
29
- withCredentials,
30
- })
31
- }
@@ -1,17 +0,0 @@
1
- const assign = require('object-assign')
2
-
3
- function ProjectsClient(client) {
4
- this.client = client
5
- }
6
-
7
- assign(ProjectsClient.prototype, {
8
- list() {
9
- return this.client.request({uri: '/projects'})
10
- },
11
-
12
- getById(id) {
13
- return this.client.request({uri: `/projects/${id}`})
14
- },
15
- })
16
-
17
- module.exports = ProjectsClient
@@ -1,119 +0,0 @@
1
- const assign = require('object-assign')
2
- const {Observable, map, filter} = require('./util/observable')
3
- const Patch = require('./data/patch')
4
- const Transaction = require('./data/transaction')
5
- const dataMethods = require('./data/dataMethods')
6
- const DatasetsClient = require('./datasets/datasetsClient')
7
- const ProjectsClient = require('./projects/projectsClient')
8
- const AssetsClient = require('./assets/assetsClient')
9
- const UsersClient = require('./users/usersClient')
10
- const AuthClient = require('./auth/authClient')
11
- const httpRequest = require('./http/request')
12
- const getRequestOptions = require('./http/requestOptions')
13
- const {defaultConfig, initConfig} = require('./config')
14
- const validate = require('./validators')
15
-
16
- const toPromise = (observable) => observable.toPromise()
17
-
18
- function SanityClient(config = defaultConfig) {
19
- if (!(this instanceof SanityClient)) {
20
- return new SanityClient(config)
21
- }
22
-
23
- this.config(config)
24
-
25
- this.assets = new AssetsClient(this)
26
- this.datasets = new DatasetsClient(this)
27
- this.projects = new ProjectsClient(this)
28
- this.users = new UsersClient(this)
29
- this.auth = new AuthClient(this)
30
-
31
- if (this.clientConfig.isPromiseAPI) {
32
- const observableConfig = assign({}, this.clientConfig, {isPromiseAPI: false})
33
- this.observable = new SanityClient(observableConfig)
34
- }
35
- }
36
-
37
- assign(SanityClient.prototype, dataMethods)
38
- assign(SanityClient.prototype, {
39
- clone() {
40
- return new SanityClient(this.config())
41
- },
42
-
43
- config(newConfig) {
44
- if (typeof newConfig === 'undefined') {
45
- return assign({}, this.clientConfig)
46
- }
47
-
48
- if (this.observable) {
49
- const observableConfig = assign({}, newConfig, {isPromiseAPI: false})
50
- this.observable.config(observableConfig)
51
- }
52
-
53
- this.clientConfig = initConfig(newConfig, this.clientConfig || {})
54
- return this
55
- },
56
-
57
- withConfig(newConfig) {
58
- return this.clone().config(newConfig)
59
- },
60
-
61
- getUrl(uri, useCdn = false) {
62
- const base = useCdn ? this.clientConfig.cdnUrl : this.clientConfig.url
63
- return `${base}/${uri.replace(/^\//, '')}`
64
- },
65
-
66
- isPromiseAPI() {
67
- return this.clientConfig.isPromiseAPI
68
- },
69
-
70
- _requestObservable(options) {
71
- const uri = options.url || options.uri
72
-
73
- // If the `canUseCdn`-option is not set we detect it automatically based on the method + URL.
74
- // Only the /data endpoint is currently available through API-CDN.
75
- const canUseCdn =
76
- typeof options.canUseCdn === 'undefined'
77
- ? ['GET', 'HEAD'].indexOf(options.method || 'GET') >= 0 && uri.indexOf('/data/') === 0
78
- : options.canUseCdn
79
-
80
- const useCdn = this.clientConfig.useCdn && canUseCdn
81
-
82
- const tag =
83
- options.tag && this.clientConfig.requestTagPrefix
84
- ? [this.clientConfig.requestTagPrefix, options.tag].join('.')
85
- : options.tag || this.clientConfig.requestTagPrefix
86
-
87
- if (tag) {
88
- options.query = {tag: validate.requestTag(tag), ...options.query}
89
- }
90
-
91
- const reqOptions = getRequestOptions(
92
- this.clientConfig,
93
- assign({}, options, {
94
- url: this.getUrl(uri, useCdn),
95
- })
96
- )
97
-
98
- return new Observable((subscriber) =>
99
- httpRequest(reqOptions, this.clientConfig.requester).subscribe(subscriber)
100
- )
101
- },
102
-
103
- request(options) {
104
- const observable = this._requestObservable(options).pipe(
105
- filter((event) => event.type === 'response'),
106
- map((event) => event.body)
107
- )
108
-
109
- return this.isPromiseAPI() ? toPromise(observable) : observable
110
- },
111
- })
112
-
113
- SanityClient.Patch = Patch
114
- SanityClient.Transaction = Transaction
115
- SanityClient.ClientError = httpRequest.ClientError
116
- SanityClient.ServerError = httpRequest.ServerError
117
- SanityClient.requester = httpRequest.defaultRequester
118
-
119
- module.exports = SanityClient
@@ -1,13 +0,0 @@
1
- const assign = require('object-assign')
2
-
3
- function UsersClient(client) {
4
- this.client = client
5
- }
6
-
7
- assign(UsersClient.prototype, {
8
- getById(id) {
9
- return this.client.request({uri: `/users/${id}`})
10
- },
11
- })
12
-
13
- module.exports = UsersClient
@@ -1,8 +0,0 @@
1
- module.exports = (obj, defaults) =>
2
- Object.keys(defaults)
3
- .concat(Object.keys(obj))
4
- .reduce((target, prop) => {
5
- target[prop] = typeof obj[prop] === 'undefined' ? defaults[prop] : obj[prop]
6
-
7
- return target
8
- }, {})
@@ -1,17 +0,0 @@
1
- module.exports = function getSelection(sel) {
2
- if (typeof sel === 'string' || Array.isArray(sel)) {
3
- return {id: sel}
4
- }
5
-
6
- if (sel && sel.query) {
7
- return 'params' in sel ? {query: sel.query, params: sel.params} : {query: sel.query}
8
- }
9
-
10
- const selectionOpts = [
11
- '* Document ID (<docId>)',
12
- '* Array of document IDs',
13
- '* Object containing `query`',
14
- ].join('\n')
15
-
16
- throw new Error(`Unknown selection - must be one of:\n\n${selectionOpts}`)
17
- }
@@ -1,11 +0,0 @@
1
- // Since `@sanity/client` doesn't offer ESM exports (yet) const {filter} = require('rxjs/operators') will cause the the whole of rxjs to be included in the bundle.
2
- // The internal import paths here is a stop-gap measure and will become less of a problem when @sanity/client export tree-shakeable esm bundles
3
- const {Observable} = require('rxjs/internal/Observable')
4
- const {filter} = require('rxjs/internal/operators/filter')
5
- const {map} = require('rxjs/internal/operators/map')
6
-
7
- module.exports = {
8
- Observable,
9
- filter,
10
- map,
11
- }
package/src/util/once.js DELETED
@@ -1,12 +0,0 @@
1
- module.exports = (fn) => {
2
- let didCall = false
3
- let returnValue
4
- return (...args) => {
5
- if (didCall) {
6
- return returnValue
7
- }
8
- returnValue = fn(...args)
9
- didCall = true
10
- return returnValue
11
- }
12
- }
package/src/util/pick.js DELETED
@@ -1,9 +0,0 @@
1
- module.exports = (obj, props) =>
2
- props.reduce((selection, prop) => {
3
- if (typeof obj[prop] === 'undefined') {
4
- return selection
5
- }
6
-
7
- selection[prop] = obj[prop]
8
- return selection
9
- }, {})