@cap.core/connect 0.0.0-stage → 1.1.3

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,131 @@
1
+
2
+ export function uri4 ({ SELECT }) {
3
+ const path = path4 (SELECT.from)
4
+ const query = query4 (SELECT)
5
+ return path + query
6
+ }
7
+
8
+ export function path4 ({ref}) {
9
+ return ref.map (r => {
10
+ if (!r.id) return '/'+ encodeURIComponent(r)
11
+ const filter = []
12
+ for (let i=0; i < r.where.length; i++) {
13
+ let x = r.where[i]
14
+ if ('val' in x) {
15
+ filter.push (encodeURIComponent(val(x)))
16
+ continue
17
+ }
18
+ let eq = r.where[++i], v = r.where[++i]
19
+ if (eq === '=' && x.ref?.length === 1 && 'val' in v) {
20
+ filter.push (x.ref + '=' + encodeURIComponent(val(v)))
21
+ if (/^AND$/i.test(r.where[i+1])) ++i // skip 'and' operator
22
+ }
23
+ else throw new Error (`OData expects filter expressions to be of the form 'property = value'`)
24
+ }
25
+ return '/'+ encodeURIComponent(r.id) + '('+ filter +')'
26
+ }).join('')
27
+ }
28
+
29
+
30
+ export function query4 ({ columns, where, groupBy, orderBy, limit }) {
31
+ const query={}
32
+ if (columns) Object.assign (query, $select(columns))
33
+ if (where) Object.assign (query, $filter(where))
34
+ if (groupBy) query.$apply = $groupby(groupBy)
35
+ if (orderBy) query.$orderby = $orderby(orderBy)
36
+ if (limit?.rows) query.$top = expr(limit.rows)
37
+ if (limit?.offset) query.$skip = expr(limit.offset)
38
+ const options = Object.entries(query).map (([k,v]) => k + '=' + encodeURIComponent(v))
39
+ if (options.length) return '?'+ options.join('&')
40
+ else return ''
41
+ }
42
+
43
+
44
+ const $select = cols => {
45
+ const selects=[], expands=[]
46
+ cols.forEach (c => {
47
+ if ('expand' in c) return expands.push ($expand(c))
48
+ if ('ref' in c && !('val' in c) && !('list' in c)) return selects.push(ref(c))
49
+ else throw new Error (`OData $select expects columns to be of the form 'ref' or 'expand'`)
50
+ })
51
+ const query = {}
52
+ if (selects.length) query.$select = selects.join(',')
53
+ if (expands.length) query.$expand = expands.join(',')
54
+ return query
55
+ }
56
+
57
+ const $expand = c => {
58
+ if (c.expand == '*') return ref(c)
59
+ const options = Object.entries($select(c.expand)).map (([k,v]) => k + '=' + v)
60
+ return ref(c) + '(' + options.join(';') + ')'
61
+ }
62
+
63
+ const $filter = where => {
64
+ const filter = [], search = [], query = {}
65
+ !function filter4 (where) {
66
+ for (let i = 0; i < where.length; i++) {
67
+ let x = where[i]
68
+ if (x.ref?.length === 1 && x.ref[0] === '$search' && /^like$/i.test(where[i+1])) {
69
+ search.push (where[i+2].val)
70
+ // Remove the adjoining AND along with the search predicate.
71
+ if (filter.length) filter.pop(); else if (/^and$/i.test(where[i+3])) ++i
72
+ i += 2
73
+ }
74
+ else if (x === 'like') filter.push (like(filter.pop(), where[++i]))
75
+ else if (typeof x === 'string') filter.push (lgtneq[x] || x)
76
+ else if ('xpr' in x) { filter.push('('); filter4(x.xpr); filter.push(')') }
77
+ else filter.push (expr(x))
78
+ }
79
+ } (where)
80
+ if (filter.length) query.$filter = filter.join(' ')
81
+ if (search.length) query.$search = search.join(' ')
82
+ return query
83
+ }
84
+
85
+
86
+ const $groupby = () => {
87
+ throw new Error(`OData client doesn't support groupBy yet`)
88
+ }
89
+
90
+ const $orderby = cols => cols.map(oc => {
91
+ let s = expr(oc)
92
+ return !oc.sort ? s : s + ' ' + oc.sort
93
+ }).join(',')
94
+
95
+ const lgtneq = {
96
+ '=' : 'eq',
97
+ '==' : 'eq',
98
+ '!=' : 'ne',
99
+ '<' : 'lt',
100
+ '<=' : 'le',
101
+ '>' : 'gt',
102
+ '>=' : 'ge',
103
+ }
104
+
105
+ const expr = x => {
106
+ if ('val' in x) return val(x)
107
+ if ('list' in x) return list(x)
108
+ if ('ref' in x) return ref(x)
109
+ if ('func' in x) return func(x)
110
+ else throw new Error (`OData expects expressions to be of the form 'ref', 'val', 'list', or 'func'`)
111
+ }
112
+
113
+ const ref = ({ref}) => ref.join('/')
114
+ const val = ({val}) => typeof val === 'string' ? str(val) : val
115
+ const list = ({list}) => `(${list.map(expr).join(',')})`
116
+ const func = ({func,args}) => func + list({list:args})
117
+ const str = val => `'${val.replaceAll("'", "''")}'`
118
+
119
+ const like = (ref,{val}) => {
120
+ let contains = 'contains'
121
+ ref = `tolower(${ref})`
122
+ val = val.toLowerCase()
123
+ if (val.at(0) === '%') {
124
+ if (val.at(-1) === '%') val = val.slice(1,-1)
125
+ else [contains, val] = ['endswith', val.slice(1)]
126
+ } else {
127
+ if (val.at(-1) !== '%') ; // do a contains (unlike SQL's like)
128
+ else [contains, val] = ['startswith', val.slice(0,-1)]
129
+ }
130
+ return `${contains}(${ref},${str(val)})`
131
+ }
@@ -0,0 +1,115 @@
1
+ import { Service } from '../service.js'
2
+ import { RemoteErrors } from './errors.js'
3
+
4
+ /**
5
+ * The base class for service proxies consuming remote services over HTTP.
6
+ */
7
+ export class RemoteService extends Service {
8
+
9
+ static defaults = {
10
+ server: '' // REVISIT: to be replaced by `cds.requires.<srv>`.
11
+ }
12
+
13
+ get kind() { return 'http' }
14
+
15
+ constructor (uri, options, defaults = RemoteService.defaults) {
16
+ super().uri = uri == '/' ? '' : uri
17
+ if (options) this.options = {
18
+ ...defaults, ...options, headers: headers4 (defaults.headers, options.headers)
19
+ }
20
+ }
21
+
22
+
23
+ /**
24
+ * @private Fetch CSRF token asynchronously.
25
+ */
26
+ async csrf_token() {
27
+ try {
28
+ const o = this.options4 ('HEAD', { headers: {'x-csrf-token':'fetch'} })
29
+ const res = await fetch (this.uri, o)
30
+ return res.headers.get('x-csrf-token') || false
31
+ } catch {
32
+ return false
33
+ }
34
+ }
35
+
36
+
37
+ /**
38
+ * Prepare request options for the HTTP request.
39
+ */
40
+ options4 (method, options, data) {
41
+ const defaults = this.options || RemoteService.defaults
42
+ const o = {
43
+ method, ...defaults, ...options, headers: headers4 (defaults.headers, options?.headers)
44
+ }
45
+ if (o.auth) {
46
+ let credentials = `${o.auth.username||''}:${o.auth.password||''}`
47
+ o.headers.authorization ??= `Basic ${btoa(credentials)}`
48
+ }
49
+ if (data !== undefined) {
50
+ o.body = JSON.stringify (data)
51
+ o.headers['content-type'] ??= 'application/json'
52
+ }
53
+ return o
54
+ }
55
+
56
+
57
+ /** Send positional data and options; pass undefined for data in options-only requests. */
58
+ async send (method, path, data, options, ...tail) {
59
+
60
+ // Canonicalize the path, data, and options arguments
61
+ if (typeof path !== 'string') [ path, data, options ] = path?.raw
62
+ ? [ String.raw (path, data, options, ...tail) ]
63
+ : [ '', path, data ]
64
+ if (method === 'QUERY') method = 'POST' // for the time being
65
+
66
+ // Prepare request options
67
+ const uri = this.uri + (path[0] === '/' ? path : '/'+ path)
68
+ const o = this.options4 (method, options, data)
69
+
70
+ // CSRF pre-flight
71
+ const csrf = this._csrf_token ??= this.csrf_token()
72
+ if (csrf) o.headers['x-csrf-token'] ??= await csrf || undefined
73
+
74
+ // Send the request
75
+ const res = await fetch (uri,o)
76
+
77
+ // Handle responses based on content type and status
78
+ if (res.status === 204) return null
79
+ if (/^application\/json/.test(res.headers.get('content-type'))) {
80
+ if (res.ok) return await this.reply (res)
81
+ else throw await this.error (res)
82
+ } else return res // leave all others to callers
83
+ }
84
+
85
+
86
+ /**
87
+ * Handle successful response from the server. The default implementation
88
+ * simply returns the parsed JSON body, and stores that in `res.body.parsed`.
89
+ * Subclasses may override this method to provide appropriate custom handling.
90
+ */
91
+ async reply (res) {
92
+ return res.body.parsed = await res.json()
93
+ }
94
+
95
+
96
+ /**
97
+ * Handle error response from the server. The default implementation extracts
98
+ * the `errors` from the JSON body and returns a RemoteErrors instance.
99
+ * Subclasses may override this method to provide appropriate custom handling.
100
+ * @param {object} [_body] - Optional pre-parsed JSON body provided by subclasses.
101
+ */
102
+ async error (res, _body) {
103
+ const body = res.body.parsed ??= _body ?? await res.json()
104
+ if (!body.errors) return new Error (`Unknown error occurred`)
105
+ else return new RemoteErrors (body.errors, res, this.send)
106
+ }
107
+ }
108
+
109
+
110
+ // Normalize fetch-compatible headers and merge them case-insensitively.
111
+ const headers4 = (...sources) => {
112
+ const headers = new Headers
113
+ for (const source of sources) new Headers(source).forEach ((v,k) => headers.set(k,v))
114
+ return Object.fromEntries(headers)
115
+ }
@@ -0,0 +1,28 @@
1
+
2
+ export class RemoteErrors extends AggregateError {
3
+ constructor (errors, response, caller) {
4
+ if (errors.length > 1) super(errors) .for (response, caller)
5
+ else return new RemoteError (errors[0], response, caller)
6
+ }
7
+ }
8
+
9
+
10
+ export class RemoteError extends Error {
11
+
12
+ constructor (error, response, caller) {
13
+ Object.assign (super(),error) .for (response, caller)
14
+ }
15
+
16
+ for (response, caller) {
17
+ this.message ||= response.statusText
18
+ this.status ||= response.status
19
+ if (response) Object.defineProperty (this, 'response', { value: response })
20
+ if (caller) Error.captureStackTrace?.(this, caller)
21
+ return this
22
+ }
23
+ }
24
+
25
+
26
+ RemoteErrors.prototype.for = RemoteError.prototype.for
27
+ RemoteErrors.prototype.name = 'RemoteErrors'
28
+ RemoteError.prototype.name = 'RemoteError'
@@ -0,0 +1,27 @@
1
+ import { RemoteService } from './client.js'
2
+
3
+ export default class HcqlService extends RemoteService {
4
+ get kind() { return 'hcql' }
5
+
6
+ async describe (...names) {
7
+ return await this.send ('GET', '/?describe='+ names)
8
+ }
9
+
10
+ run (query, ...args) {
11
+ // Remove `param` and `ref` properties from query parameters, as the HCQL
12
+ // service might be an older version that doesn't support them.
13
+ if (query.params) for (let p of query.params) {
14
+ delete p.param
15
+ delete p.ref
16
+ }
17
+ return super.run (query, ...args)
18
+ }
19
+
20
+ async reply (res) {
21
+ const body = await super.reply (res); if (!body) return body
22
+ const data = body.data; if (!data) return body
23
+ if ('affected' in body)
24
+ data.affected = body.affected
25
+ return data
26
+ }
27
+ }
@@ -0,0 +1,77 @@
1
+ import { path4, query4 } from './adapters/cqn2odata.js'
2
+ import { RemoteService } from './client.js'
3
+ const $set = (o,k,v) => Object.defineProperty(o,k,{ value:v, enumerable:true, writable:true, configurable:true })
4
+
5
+ export default class ODataService extends RemoteService {
6
+ get kind() { return 'odata' }
7
+
8
+ run (query, ...args) {
9
+ const handler = this ['on_' + query.kind]
10
+ if (!handler) return super.run (query, ...args)
11
+ else return handler.call (this, query, ...args)
12
+ }
13
+
14
+ async on_SELECT ({ SELECT }) {
15
+ const entity = path4 (SELECT.from)
16
+ // Only collection URLs need a limit; keyed URLs already identify one entity.
17
+ if (SELECT.one && !SELECT.from.ref.at(-1)?.where) SELECT = {
18
+ ...SELECT, limit: {
19
+ ...SELECT.limit, rows: { val: Math.min(SELECT.limit?.rows?.val ?? 1, 1) }
20
+ }
21
+ }
22
+ const query = query4 (SELECT)
23
+ const data = await this.get (entity + query)
24
+ return SELECT.one && Array.isArray(data) ? data[0] ?? null : data
25
+ }
26
+
27
+ on_INSERT ({ INSERT }) {
28
+ const entity = path4 (INSERT.into)
29
+ if (INSERT.entries?.length > 1)
30
+ return Promise.all (INSERT.entries.map (e => this.post (entity,e)))
31
+ return this.post (entity, INSERT.entries[0])
32
+ }
33
+
34
+ on_UPSERT () {
35
+ throw new Error (`UPSERT is not supported by the '${this.kind}' client`)
36
+ }
37
+
38
+ on_UPDATE ({ UPDATE }) {
39
+ if (UPDATE.where?.length) throw new Error (`Updates with where clauses are not supported; use a key-addressed entity instead`)
40
+ const subject = path4 (UPDATE.entity)
41
+ return this.patch (subject, merge (UPDATE.data, UPDATE.with))
42
+ }
43
+
44
+ on_DELETE ({ DELETE }) {
45
+ if (DELETE.where?.length) throw new Error (`Deletes with where clauses are not supported; use a key-addressed entity instead`)
46
+ const entity = path4 (DELETE.from)
47
+ return this.delete (entity)
48
+ }
49
+
50
+ async reply (res) {
51
+ const body = await super.reply (res)
52
+ return body.value || body
53
+ }
54
+
55
+ async error (res) {
56
+ const body = await res.json()
57
+ if (body?.error)
58
+ body.errors ??= body.error.details?.length ? body.error.details : [body.error]
59
+ return super.error (res, body)
60
+ }
61
+
62
+ }
63
+
64
+
65
+ /**
66
+ * Merges the changes from UPDATE.set into the data object, throwing an error
67
+ * if any change uses an expression or reference.
68
+ */
69
+ const merge = (data={}, changes) => {
70
+ for (let k in changes) {
71
+ let v = changes[k].val
72
+ if (v === undefined)
73
+ throw new Error (`Updates with expressions are not supported`)
74
+ else $set(data,k,v)
75
+ }
76
+ return data
77
+ }
@@ -0,0 +1,5 @@
1
+ import ODataService from './odata.js'
2
+
3
+ export default class RestService extends ODataService {
4
+ get kind() { return 'rest' }
5
+ }
package/lib/connect.js ADDED
@@ -0,0 +1,131 @@
1
+ // @ts-check
2
+ // We load the necessary client modules eagerly to enable rolldown of service kinds.
3
+ import { RemoteService } from './clients/client.js'
4
+ import hcql from './clients/hcql.js'
5
+ import rest from './clients/rest.js'
6
+ import odata from './clients/odata.js'
7
+
8
+ /**
9
+ * Provides the `cds.connect.to` function to create service clients for remote CAP services.
10
+ */
11
+ export const connect = {
12
+
13
+ /**
14
+ * @public Connect to a remote service by its name or URL, optionally choosing the protocol.
15
+ * @example
16
+ * import cds from '@cap.core/connect'
17
+ * const srv = await cds.connect.to `http://localhost:4004/hcql/browse`
18
+ * const srv = await cds.connect.to `/hcql/browse`
19
+ * const srv = await cds.connect.to `CatalogService`
20
+ * const srv = await cds.connect.to (`CatalogService`,'odata')
21
+ * const srv = await cds.connect.to (`CatalogService`, { kind: 'odata' })
22
+ * @param { TemplateStringsArray | string } name_or_uri The name or uri of a service to connect to.
23
+ * @param { options } [options] The options to init newly created service clients with.
24
+ * @param { any } etc Potential arguments for template interpolation.
25
+ * @returns { Promise<RemoteService> } The connected service instance.
26
+ * @typedef { { kind?: string, [key:string]: any } | string | undefined } options
27
+ */
28
+ async to (name_or_uri, options, ...etc) {
29
+
30
+ // If the name_or_uri is a template string, convert it to a string and reset options.
31
+ if (typeof name_or_uri !== 'string')
32
+ [ name_or_uri, options ] = [ String.raw (name_or_uri, options, ...etc), undefined ]
33
+
34
+ // Determine the uri vs name, and the chosen kind of service, if any.
35
+ let [, uri, name ] = /^((?:https?:\/)?\/.*)$/.exec (name_or_uri) || [0,'',name_or_uri]
36
+ let kind = typeof options === 'string' ? options : options?.kind
37
+ if (options === kind) options = undefined
38
+
39
+ // If called with a name, return a prior cached instance, or resolve url from catalog.
40
+ let key; if (uri) key = uri; else {
41
+ let srv = this.cached (key = !kind ? name : `${name}:${kind}`, options)
42
+ if (srv) return srv; else [ uri, kind ] = await this.resolve (name, kind)
43
+ }
44
+
45
+ // Return a prior cached instance or create and cache a new one on 1st connect.
46
+ let srv = this.cached (uri, options)
47
+ if (srv) return services[key] = srv instanceof Promise ? srv.then (s => services[key] = s) : srv
48
+ else return services[key] = services[uri] = this.service4 (uri, options, kind) .then (
49
+ service => services[key] = services[uri] = service
50
+ )
51
+ },
52
+
53
+
54
+ /**
55
+ * @private Looks up and returns a cached entry for `key`, if any.
56
+ * @param { string } key The cache key (name, `name:kind`, or URI).
57
+ * @param { options } [options] The options object used for connecting to the service.
58
+ * @throws If called with an options object that conflicts with a cached entry.
59
+ */
60
+ cached (key, options) {
61
+ const cached = services[key]
62
+ if (cached && options && typeof options === 'object')
63
+ throw new Error (`Cannot re-connect to '${key}' with potentially conflicting options.`)
64
+ return cached
65
+ },
66
+
67
+
68
+ /**
69
+ * @private Resolves the service by its name against the server's service catalog.
70
+ * @param {string} name The name of the service to resolve.
71
+ * @param {string} [kind] The preferred kind of service to resolve.
72
+ * @throws If the service is not found or doesn't serve the requested protocol.
73
+ * @returns The resolved endpoint URL and protocol kind.
74
+ */
75
+ async resolve (name, kind) {
76
+
77
+ // Fetch the service catalog for the server, caching the promise to avoid duplicate requests.
78
+ const server = this.defaults.server // pin the server early to ensure consistency across awaits.
79
+ const catalog = catalogs[server] ??= fetch (server + '/?services') .then (r => r.json())
80
+ const { [name]: service } = await catalog
81
+ if (!service) throw new Error(`Unknown service: ${name}`)
82
+
83
+ // Determine the kind of service to use based on the available endpoints and options.
84
+ const protocols = kind ? [kind] : [ 'hcql', 'rest', 'odata' ]
85
+ const served = protocols.find (k => k in service.endpoints)
86
+ if (!served) throw new Error(`Service '${name}' doesn't serve protocol(s): ${protocols}`)
87
+
88
+ // Get and return the resolved url with the served protocol.
89
+ const url = server + service.endpoints [served]
90
+ return [ url, served ]
91
+ },
92
+
93
+
94
+ /**
95
+ * @private Factory function to create a service instance based on its kind.
96
+ * @param { string } uri The URI of the service endpoint.
97
+ * @param { options } o The options object for the service client.
98
+ * @param { string } kind The service kind.
99
+ * @returns { Promise<RemoteService> }
100
+ */
101
+ async service4 (uri, o, kind = /\/(hcql|odata|rest)\//.exec(uri)?.[1] ?? 'hcql') {
102
+ const client = kinds[kind]; if (!client) throw new Error(`Unsupported service kind: ${kind}`)
103
+ return new client (uri,o)
104
+ },
105
+
106
+
107
+ /**
108
+ * Default options for connecting to services, and sending requests.
109
+ */
110
+ get defaults() { return RemoteService.defaults },
111
+ set defaults(o) { RemoteService.defaults = o },
112
+ }
113
+
114
+
115
+ /**
116
+ * A registry and cache for connected services, supporting idempodent connects.
117
+ * Entries are keyed by resolved endpoint URI and, for name-based connects, by
118
+ * the service name (unspecified kind) or `name:kind` (specified kind). Name
119
+ * keys alias the URI-keyed instance. The first connection's options take precedence.
120
+ * @type {{ [k:string]: RemoteService | Promise<RemoteService> }}
121
+ */
122
+ export const services = {}
123
+
124
+ /**
125
+ * A registry for service kinds
126
+ * @type {{ [k:string]: typeof RemoteService }}
127
+ */
128
+ export const kinds = { hcql, rest, odata }
129
+
130
+ /** @type {{ [server:string]: Promise<any> }} */
131
+ const catalogs = Object.create(null)
package/lib/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import { cql, cql as ql } from '@cap.core/ql'
2
+ import { Service } from './service.js'
3
+ import { connect } from './connect.js'
4
+ export { Service, connect, cql, ql } //> supports 1, 2, 4 below
5
+ export default { Service, connect, cql, ql } //> supports 3, 5 below
6
+
7
+ // 1. import { Service, connect, cql, ql } from '@cap.core/connect'
8
+ // 2. const { Service, connect, cql, ql } = require('@cap.core/connect')
9
+ // 3. const { default: cds } = require('@cap.core/connect')
10
+ // 4. const cds = require('@cap.core/connect')
11
+ // 5. import cds from '@cap.core/connect'
package/lib/service.js ADDED
@@ -0,0 +1,80 @@
1
+ // @ts-check
2
+ import { SELECT, INSERT, UPSERT, UPDATE, DELETE, Query } from '@cap.core/ql'
3
+
4
+ /**
5
+ * Standard CAP Service API, around the central methods `send(req)` and `run(query)`.
6
+ * Complemented by convenient REST and CRUD-style methods.
7
+ * @typedef {'GET'|'PUT'|'POST'|'PATCH'|'DELETE'|'OPTIONS'|'QUERY'|'HEAD' } HTTP
8
+ */
9
+ export class Service {
10
+
11
+ /**
12
+ * The central method for sending requests to be processed by the service.
13
+ * Subclasses implement this method to handle actual requests.
14
+ * @param { HTTP } method - The HTTP method to use for the request.
15
+ * @param { any[] } args - The arguments for the HTTP request.
16
+ * @returns { Promise<any> }
17
+ */
18
+ send (method, ...args) { // eslint-disable-line no-unused-vars
19
+ throw new Error('Subclass must implement the send method')
20
+ }
21
+
22
+ /**
23
+ * The central method for executing queries. The query can be either a plain CQL
24
+ * string, a tagged template literal, or an already constructed CQN object.
25
+ * @param { TemplateStringsArray & Query } query - The query to execute.
26
+ * @param { any[] } args - Binding arguments for the query.
27
+ */
28
+ run (query, ...args) {
29
+ if (query.raw || typeof query === 'string') // tagged template literal or plain cql string
30
+ return Query.for(query,...args).for(this) // starts constructing a query; subsequent await calls this.run(q) again
31
+ return this.send ('QUERY', query, ...args) // constructed query comes here for execution
32
+ }
33
+
34
+ // CRUD-style convenience shortcuts
35
+ read (/** @type any[] */..._) { return SELECT(..._).for(this) }
36
+ create (/** @type any[] */..._) { return INSERT(..._).for(this) }
37
+ insert (/** @type any[] */..._) { return INSERT.entries(..._).for(this) }
38
+ upsert (/** @type any[] */..._) { return UPSERT.entries(..._).for(this) }
39
+ update (/** @type any[] */..._) { return UPDATE(..._).for(this) }
40
+ exists (/** @type any[] */..._) { return SELECT.one(1).from(..._).for(this) }
41
+
42
+ // REST-style convenience shortcuts
43
+ get (/** @type any[] */..._) { return rest_qry ('GET', SELECT, this, ..._) }
44
+ put (/** @type any[] */..._) { return this.send('PUT', ..._) }
45
+ post (/** @type any[] */..._) { return this.send('POST', ..._) }
46
+ patch (/** @type any[] */..._) { return this.send('PATCH', ..._) }
47
+ delete (/** @type any[] */..._) { return rest_qry ('DELETE', DELETE, this, ..._) }
48
+
49
+ // REST verb convenience shortcuts
50
+ get QUERY() { return (/** @type any[] */ ..._) => this.send ('QUERY', ..._) }
51
+ get GET() { return (/** @type any[] */ ..._) => this.get (..._) }
52
+ get PUT() { return (/** @type any[] */ ..._) => this.put (..._) }
53
+ get POST() { return (/** @type any[] */ ..._) => this.post (..._) }
54
+ get PATCH() { return (/** @type any[] */ ..._) => this.patch (..._) }
55
+
56
+ // CRUD verb convenience shortcuts
57
+ get SELECT() { return (/** @type any[] */ ..._) => this.read (..._) }
58
+ get INSERT() { return (/** @type any[] */ ..._) => this.insert (..._) }
59
+ get UPSERT() { return (/** @type any[] */ ..._) => this.upsert (..._) }
60
+ get UPDATE() { return (/** @type any[] */ ..._) => this.update (..._) }
61
+ get DELETE() { return (/** @type any[] */ ..._) => this.delete (..._) }
62
+
63
+ // Shortcut for: @example let { GET, srv } = cds.connect.to `...`
64
+ get srv() { return this }
65
+
66
+ // Reflection API to introspect the service's entities and actions
67
+ get entities() { return dummy }
68
+ get actions() { return dummy }
69
+ }
70
+ const dummy = new Proxy({}, { get:(_,p) => p })
71
+
72
+
73
+ /**
74
+ * Helper to send REST requests for paths starting with '/', otherwise constructs `query`.
75
+ * @type {<T extends new() => any>(m:HTTP, query:T, srv:Service, ..._:any[]) => InstanceType<T> & Promise<any>}
76
+ */
77
+ const rest_qry = (m, query, srv, ...args) => { const x = args[0] // @ts-ignore
78
+ if ((x.raw ? x[0] : x)[0] === '/') return srv.send (m, ...args) // @ts-ignore
79
+ else return query(...args).for(srv)
80
+ }
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "@cap.core/connect",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.3",
4
+ "description": "Minimalistic cds.connect and service clients carved out from CAP.",
5
+ "repository": "https://github.com/cap-js/core.git",
6
+ "author": "daniel.hutzel@sap.com",
7
+ "type": "module",
8
+ "main": "lib/index.js",
9
+ "files": ["lib"],
10
+ "dependencies": {
11
+ "@cap.core/ql": "^2.5.7"
12
+ },
13
+ "scripts": {
14
+ "rolldown": "npx rolldown lib/index.js -o out/cap.core-connect.js"
15
+ },
16
+ "license": "Apache-2.0"
17
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.