@cap-js/cds-types
Version:
Type definitions for main packages of CAP, like `@sap/cds`
1,848 lines (1,552 loc) • 104 kB
TypeScript
declare module '@sap/cds' {
export * from "@sap/cds-dk";
export type __any_ = classes.any_
export type __array = classes.array
export type __aspect = classes.aspect
export type __Association = classes.Association
export type __Binary = classes.Binary
export type __Boolean = classes.Boolean
export type __Composition = classes.Composition
export type __context_ = classes.context_
export type __Date = classes.Date
export type __date = classes.date
export type __DateTime = classes.DateTime
export type __Decimal = classes.Decimal
export type __Double = classes.Double
export type __entity = classes.entity
export type __Float = classes.Float
export type __Int16 = classes.Int16
export type __Int32 = classes.Int32
export type __Int64 = classes.Int64
export type __Integer = classes.Integer
export type __LargeBinary = classes.LargeBinary
export type __LargeString = classes.LargeString
export type __scalar = classes.scalar
export type __service = classes.service_
export type __String = classes.String
export type __struct = classes.struct
export type __Time = classes.Time
export type __TimeStamp = classes.TimeStamp
export type __type = classes.type
export type __UInt8 = classes.UInt8
export type __UUID = classes.UUID
export type __Vector = classes.Vector
class action extends any_<'action' | 'function'> {}
export interface ActionEventHandler<S, P, R> {
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
(req: Omit<Request_2, 'data'> & { data: P, subject: S }, next: Function): Promise<R> | R
}
interface And {
and: TaggedTemplateQueryPart<this>
& ((predicate: object) => this)
& ((...expr: any[]) => this)
}
/**
* Subclass representing unauthenticated users.
*/
export class Anonymous extends User {
constructor ()
is (): boolean
}
const any: typeof any_;
interface any_ extends csn.any_ {}
class any_<K extends kinds = kinds> {
private _: K // break covariance
constructor (...aspects: any[])
readonly name: string
// parked, might be deprecated
// is (kind: kinds | 'Association' | 'Composition'): boolean
}
interface any__2 {
kind?: kinds
/**
* only available when compiled with docs:true
* @see [capire docs](https://cap.cloud.sap/docs/cds/cdl#comments)
*/
doc?: string
}
/**
* The {@link https://expressjs.com/en/4x/api.html#app| express.js application} constructed by the server implementation.
*
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-server#cds-app)
*/
export const app: import('express').Application;
export class ApplicationService extends Service {
new<T extends Constructable>(draft: T, data: {[K in keyof InstanceType<T>]?: InstanceType<T>[K]}): Promise<unknown>
new<T extends Constructable>(draft: T): {
for(keys: Key[]): Promise<unknown>,
}
discard(draft: Constructable, keys: Key[]): Promise<unknown>
edit(draft: Constructable, keys: Key[]): Promise<unknown>
save(draft: Constructable, keys: Key[]): Promise<unknown>
}
export class array extends type<'type' | 'elements'> { }
interface ArrayConstructable<T = any> {
new(...args: any[]): T[]
}
class aspect<K extends kinds = 'aspect'> extends type<K> implements WithElements {
elements: Definitions<type<'type'>>
}
/**
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#cds-association)
*/
export interface Association extends Omit<csn.Association, 'type' | 'items'> {}
export class Association extends type {
_target: entity
isAssociation: true
is2one: boolean
is2many: boolean
}
interface Association_2 extends type_2 {
target: FQN
/**
* The specified cardinality. to-one = `{max:1}`, to-many = `{max:'*'}`
*/
cardinality?: { src?: 1, min?: 1 | 0, max?: 1 | '*' }
/**
* The parsed on condition in case of unmanaged Associations
*/
on?: predicate
/**
* The optionally specified keys in case of managed Associations
*/
keys?: (ref & { as: string })[]
}
type Awaitable<T, I> = T & Promise<I>
class Axios {
get axios (): import('axios').AxiosInstance
get: import('axios').AxiosInstance['get'] & TaggedTemplateRequest
put: import('axios').AxiosInstance['put'] & TaggedTemplateRequest
post: import('axios').AxiosInstance['post'] & TaggedTemplateRequest
patch: import('axios').AxiosInstance['patch'] & TaggedTemplateRequest
delete: import('axios').AxiosInstance['delete'] & TaggedTemplateRequest
options: import('axios').AxiosInstance['options'] & TaggedTemplateRequest
get GET (): Axios['get']
get PUT (): Axios['put']
get POST (): Axios['post']
get PATCH (): Axios['patch']
get DELETE (): Axios['delete']
get OPTIONS (): Axios['options']
}
class Binary extends string { }
const boolean: typeof boolean_;
class boolean_ extends scalar { }
class Boolean_2 extends boolean { }
export const builtin: {
/**
* @see {@link models.linked.classes}
*/
classes: typeof models.linked.classes,
types: Record<string, object>, // FIXME: value should be any class part of linked.classes
};
interface ByKey {
byKey (primaryKey?: PK): this
}
export type CDL = string
namespace cds {
export {
log,
debug,
test,
ql,
QLExtensions,
csn,
delete_ as delete,
version,
home,
root,
cli,
requires,
extend,
lazify,
lazified,
entity,
event,
type,
array,
struct,
Association,
Composition,
builtin,
on,
once,
exit,
_cds,
cds_services,
connect,
server,
serve,
services,
service,
cds_serve_fluent,
cds_connect_options,
Middlewares,
middlewares,
app,
env,
_TODO,
get,
load,
resolve,
minify,
reflect,
_flavor,
_odata_options,
_options,
JSON_2 as JSON,
YAML,
CDL,
SQL,
XML,
EDM,
EDMX,
filename,
model,
parse,
linked,
__type,
__aspect,
__any_,
__scalar,
__Boolean,
__UUID,
__String,
__LargeString,
__Binary,
__LargeBinary,
__Vector,
__Integer,
__UInt8,
__Int16,
__Int32,
__Int64,
__Float,
__Double,
__Decimal,
__date,
__Date,
__Time,
__DateTime,
__TimeStamp,
__array,
__struct,
__context_,
__service,
__entity,
__Association,
__Composition,
compile,
spawn,
Key,
QueryAPI,
PropertiesOf,
Send,
FluentScheduling,
Service,
ApplicationService,
MessagingService,
RemoteService,
DatabaseService,
Transaction,
ResultSet,
ServiceImpl,
EventHandler,
OnEventHandler,
OnErrorHandler,
Partial_2 as Partial,
OneOrMany,
CdsFunction,
CdsFunctions,
HandlerFunction,
CRUDEventHandler,
ActionEventHandler,
ResultsHandler,
SpawnEvents,
SpawnEventEmitter,
types,
SpawnOptions,
context,
tx,
entities,
run,
foreach,
stream,
read,
create,
insert,
update,
transaction,
db,
queued,
unqueued,
outboxed,
unboxed,
EventContext,
Event_2 as Event,
Request_2 as Request,
User,
Anonymous,
Privileged,
utils,
Query,
SELECT_2 as SELECT,
INSERT_2 as INSERT,
UPSERT_2 as UPSERT,
UPDATE_2 as UPDATE,
DELETE_2 as DELETE,
CREATE_2 as CREATE,
DROP_2 as DROP,
primitive,
data,
name,
source,
column_expr,
predicate,
ordering_term,
expr,
ref,
_segment,
_named,
val,
xpr,
_xpr,
operator,
function_call,
enum_literal,
expr_literal,
Texts,
I18nBundle,
I18nFacade,
I18nFilesOptions,
I18nFiles,
i18n
}
}
export default cds;
export type _cds = typeof cds_2
namespace cds_2 {
export {
cds as default,
log,
debug,
test,
ql,
QLExtensions,
csn,
delete_ as delete,
version,
home,
root,
cli,
requires,
extend,
lazify,
lazified,
entity,
event,
type,
array,
struct,
Association,
Composition,
builtin,
on,
once,
exit,
_cds,
cds_services,
connect,
server,
serve,
services,
service,
cds_serve_fluent,
cds_connect_options,
Middlewares,
middlewares,
app,
env,
_TODO,
get,
load,
resolve,
minify,
reflect,
_flavor,
_odata_options,
_options,
JSON_2 as JSON,
YAML,
CDL,
SQL,
XML,
EDM,
EDMX,
filename,
model,
parse,
linked,
__type,
__aspect,
__any_,
__scalar,
__Boolean,
__UUID,
__String,
__LargeString,
__Binary,
__LargeBinary,
__Vector,
__Integer,
__UInt8,
__Int16,
__Int32,
__Int64,
__Float,
__Double,
__Decimal,
__date,
__Date,
__Time,
__DateTime,
__TimeStamp,
__array,
__struct,
__context_,
__service,
__entity,
__Association,
__Composition,
compile,
spawn,
Key,
QueryAPI,
PropertiesOf,
Send,
FluentScheduling,
Service,
ApplicationService,
MessagingService,
RemoteService,
DatabaseService,
Transaction,
ResultSet,
ServiceImpl,
EventHandler,
OnEventHandler,
OnErrorHandler,
Partial_2 as Partial,
OneOrMany,
CdsFunction,
CdsFunctions,
HandlerFunction,
CRUDEventHandler,
ActionEventHandler,
ResultsHandler,
SpawnEvents,
SpawnEventEmitter,
types,
SpawnOptions,
context,
tx,
entities,
run,
foreach,
stream,
read,
create,
insert,
update,
transaction,
db,
queued,
unqueued,
outboxed,
unboxed,
EventContext,
Event_2 as Event,
Request_2 as Request,
User,
Anonymous,
Privileged,
utils,
Query,
SELECT_2 as SELECT,
INSERT_2 as INSERT,
UPSERT_2 as UPSERT,
UPDATE_2 as UPDATE,
DELETE_2 as DELETE,
CREATE_2 as CREATE,
DROP_2 as DROP,
primitive,
data,
name,
source,
column_expr,
predicate,
ordering_term,
expr,
ref,
_segment,
_named,
val,
xpr,
_xpr,
operator,
function_call,
enum_literal,
expr_literal,
Texts,
I18nBundle,
I18nFacade,
I18nFilesOptions,
I18nFiles,
i18n
}
}
type _cds_2 = typeof cds_2
export interface cds_connect_options {
impl?: string
service?: string
kind?: string
model?: string | CSN
credentials?: object
}
export interface cds_serve_fluent {
from (model: string | CSN): cds_serve_fluent
to (protocol: string): cds_serve_fluent
at (path: string): cds_serve_fluent
in (app: import('express').Application): cds_serve_fluent
with (impl: ServiceImpl | string): cds_serve_fluent
// (req,res) : void
}
export interface cds_services {
[name: string]: Service
}
/**
* @beta helper
*/
export type CdsFunction = {
(...args: any[]): any,
__parameters: object,
__returns: any,
__self?: any, // the entity the function is bound to, in case of bound functions
}
/**
* @beta helper
*/
export type CdsFunctions<T> = Pick<T, { [K in keyof T]: T[K] extends CdsFunction ? K : never }[keyof T]>
namespace classes {
export {
mixin,
Protocol,
Column,
Definitions,
WithElements,
any_,
any,
aspect,
type,
scalar,
boolean,
Boolean_2 as Boolean,
string,
UUID,
String_2 as String,
LargeString,
Binary,
LargeBinary,
Vector,
number,
Integer,
UInt8,
Int16,
Int32,
Int64,
Float,
Double,
Decimal,
date,
Date_2 as Date,
Time,
DateTime,
TimeStamp,
array,
struct,
Map_3 as Map,
context_,
service_,
action,
event,
entity,
Association,
Composition,
ManagedAssociation,
MixedIn
}
}
/**
* The parsed effective `cds` CLI command and arguments.
* May be undefined if not started from the `cds` CLI.
* @see https://cap.cloud.sap/docs/node.js/cds-facade#cds-cli
*/
export const cli: {
/** Basic command like `serve` */ command?: CliCommands,
/** Positional arguments */ argv?: string[],
/** Named arguments */ options?: Record<string, any>,
} | undefined;
type CliCommands = 'add' | 'build' | 'compile' | 'deploy' | 'import' | 'init' | 'serve' | (string & {})
type Column = { ref: [string], as?: string }
export type column_expr = UnionToIntersection<expr> & { as?: name, cast?: any, expand?: column_expr[], inline?: column_expr[] }
interface Columns<T, This = undefined> {
columns:
((...col: KeyOfSingular<T>[]) => This extends undefined ? this : This)
& ((col: KeyOfSingular<T>[]) => This extends undefined ? this : This)
& ((...col: (string | column_expr)[]) => This extends undefined ? this : This)
& ((col: (string | column_expr)[]) => This extends undefined ? this : This)
& TaggedTemplateQueryPart<This extends undefined ? this : This>
}
type ColumnValue = Primitive | Readonly<Primitive[]> | SELECT<any>
/**
* Provides a set of methods to parse a given model, query or expression.
* You can also use `cds.compile(csn).to('<output>')` as a fluent variant.
*/
export const compile: {
/** Shortcut for `cds.compile.to.csn()` */
cdl (model: CDL, o?: _options): csn.CSN,
for: {
odata (model: csn.CSN, o?: _options): csn.CSN,
sql (model: csn.CSN, o?: _options): csn.CSN,
nodejs (model: csn.CSN, o?: _options): linked.LinkedCSN,
},
to: {
parsed: {
csn (files: filename[], o?: _options): Promise<csn.CSN>,
csn (model: CDL, o?: _options): csn.CSN,
},
xtended: {
csn (files: filename[], o?: _options): Promise<csn.CSN>,
csn (model: CDL, o?: _options): csn.CSN,
},
inferred: {
csn (files: filename[], o?: _options): Promise<csn.CSN>,
csn (model: CDL, o?: _options): csn.CSN,
},
csn (files: filename[], o?: _options): Promise<csn.CSN>,
csn (model: CDL, o?: _options): csn.CSN,
yml (model: csn.CSN, o?: _options): YAML,
yaml (model: csn.CSN, o?: _options): YAML,
json (model: csn.CSN, o?: _options): JSON_2,
sql (model: csn.CSN, o?: _options): SQL[],
cdl (model: csn.CSN, o?: _options): CDL | Iterable<[CDL, { file: filename }]>,
edm (model: csn.CSN, o?: _options | _odata_options): EDM | string,
edmx (model: csn.CSN, o?: _options | _odata_options): EDMX | Iterable<[EDMX, { file: filename }]>,
hdbcds (model: csn.CSN, o?: _options): SQL | Iterable<[SQL, { file: filename }]>,
hdbtable (model: csn.CSN, o?: _options): SQL | Iterable<[SQL, { file: filename }]>,
},
/** Fluent API variant */
(model: csn.CSN | CDL): {
for: {
odata (o?: _options): csn.CSN,
sql (o?: _options): csn.CSN,
},
to: {
parsed: { csn (o?: _options): csn.CSN },
xtended: { csn (o?: _options): csn.CSN },
inferred: { csn (o?: _options): csn.CSN },
csn (o?: _options): csn.CSN,
yml (o?: _options): YAML,
yaml (o?: _options): YAML,
json (o?: _options): JSON_2,
sql (o?: _options): SQL[],
cdl (o?: _options): CDL | Iterable<[CDL, { file: filename }]>,
edm (o?: _options | _odata_options): EDM | string,
edmx (o?: _options | _odata_options): EDMX | Iterable<[EDMX, { file: filename }]>,
hdbcds (o?: _options): SQL | Iterable<[SQL, { file: filename }]>,
hdbtable (o?: _options): SQL | Iterable<[SQL, { file: filename }]>,
},
},
/** Async fluent variant reading from files */
(files: filename[]): {
for: {
odata (o?: _options): Promise<csn.CSN>,
sql (o?: _options): Promise<csn.CSN>,
},
to: {
parsed: { csn (o?: _options): Promise <csn.CSN> },
xtended: { csn (o?: _options): Promise <csn.CSN> },
inferred: { csn (o?: _options): Promise <csn.CSN> },
csn (o?: _options): Promise <csn.CSN>,
yml (o?: _options): Promise <YAML>,
yaml (o?: _options): Promise <YAML>,
json (o?: _options): Promise <JSON_2>,
sql (o?: _options): Promise <SQL[]>,
cdl (o?: _options): Promise <CDL | Iterable<[CDL, { file: filename }]>>,
edm (o?: _options | _odata_options): Promise <EDM | string>,
edmx (o?: _options | _odata_options): Promise <EDMX | Iterable<[EDMX, { file: filename }]>>,
hdbcds (o?: _options): Promise <SQL | Iterable<[SQL, { file: filename }]>>,
hdbtable (o?: _options): Promise <SQL | Iterable<[SQL, { file: filename }]>>,
},
},
};
export class Composition extends Association {
isComposition: true
}
export const connect: {
/**
* Connects to a specific datasource.
* @example await cds.connect.to ('service')
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-connect#cds-connect-to)
*/
to(datasource: string, options?: cds_connect_options): Promise<Service>,
/**
* Shortcut for 'db' as the primary database returning `cds.DatabaseService`
* @example await cds.connect.to ('db')
*/
to(datasource: 'db', options?: cds_connect_options): Promise<cds_2.DatabaseService>,
/**
* Connects to a specific datasource via a Service subclass
* @example await cds.connect.to (ServiceClass)
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-connect#cds-connect-to)
*/
to<S extends Service>(datasource: {new(): S}, options?: cds_connect_options): Promise<S>,
/**
* Connects to a specific datasource via a Service class from cds-typer
* @example
* import ServiceClass from '#cds-models/SomeService'
* await cds.connect.to (ServiceClass)
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-connect#cds-connect-to)
*/
to<S>(datasource: S, options?: cds_connect_options): Promise<cds_2.CdsFunctions<S> & Service>,
/**
* Connects to a specific datasource via options.
* @example cds.connect.to ({ kind:..., impl:... })
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-connect#cds-connect-to)
*/
to(options: cds_connect_options): Promise<Service>,
/**
* Connects the primary datasource.
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-connect)
*/
// API extractor cannot handle the direct usages of the cds namespace in typeof cds, so add an indirection.
(options?: string | cds_connect_options): Promise<_cds>, // > cds.connect(<options>)
};
interface Constructable<T = any> {
new(...args: any[]): T
}
class ConstructedQuery<T> {
// branded type to break covariance for the subclasses
// that don't make explicit use of the generic. So `UPDATE<Books> !<: UPDATE<number>`
private _: T
then (_resolved: (x: any) => any, _rejected: (e: Error) => any): any
bind (service: Service): this
}
/**
* @see [docs](https://cap.cloud.sap/docs/node.js/cds-tx#event-contexts
*/
export let context: EventContext | undefined;
interface context_ extends csn.context {}
class context_ extends any_ { }
interface context_2 extends any__2 { }
namespace CQN {
export {
Query,
SELECT_2 as SELECT,
INSERT_2 as INSERT,
UPSERT_2 as UPSERT,
UPDATE_2 as UPDATE,
DELETE_2 as DELETE,
CREATE_2 as CREATE,
DROP_2 as DROP,
primitive,
data,
name,
source,
column_expr,
predicate,
ordering_term,
expr,
ref,
_segment,
_named,
val,
xpr,
_xpr,
operator,
function_call,
enum_literal,
expr_literal
}
}
export const create: Service['create'];
type CREATE_2 = { CREATE: {
entity: entity_2 | name,
as: SELECT_2,
}, }
export { CREATE_2 as CREATE }
class CREATE_3<T> extends ConstructedQuery<T> {
private constructor();
static entity (entity: EntityDescription): CREATE_3<EntityDescription>
CREATE: CQN.CREATE['CREATE']
}
export namespace CRUDEventHandler {
export type Before<P, R = P | void | Error> = (req: Request_2<P>) => Promise<R> | R
export type On<P, R = P | void | Error> = (req: Request_2<P>, next: (...args: any[]) => Promise<R> | R) => Promise<R> | R
export type After<P, R = P | void | Error> = (data: undefined | P, req: Request_2<P>) => Promise<R> | R
}
/**
* A parsed CDS model in CSN object notation.
*/
interface CSN {
/**
* The assigned namespace. If parsed from multiple sources,
* this is the topmost model's namespace, if any, not the
* ones of imported models.
*/
namespace?: string
/**
* The list of usings in this parsed model. Not available after
* imports have been resolved into a merged model.
*/
requires?: string[]
/**
* All definitions in the model including those from imported models.
*/
definitions?: Record<FQN, Definition>
/**
* All extensions in the model including those from imported models.
* Not available after extensions have been applied.
*/
extensions?: Extension[]
/**
* The names of the files from which this model has been loaded.
*/
$sources?: string[]
}
namespace csn {
export {
CSN,
FQN,
Definition,
Extension,
Element,
kinds,
any__2 as any_,
context_2 as context,
service_2 as service,
type_2 as type,
struct_2 as struct,
Map_2 as Map,
entity_2 as entity,
EntityElements,
Association_2 as Association
}
}
export { csn }
/** @private */
export type data = Record<string, any>
export class DatabaseService extends Service {
deploy (model?: csn.CSN | string): Promise<csn.CSN>
begin (): Promise<void>
commit (): Promise<void>
rollback (): Promise<void>
}
class DataUtil {
delete (db?: Service): Promise<void>
reset (db?: Service): Promise<void>
/**
* @deprecated if needed, call `reset()`, considering test performance
*/
autoReset (enabled: boolean): this
}
class date extends scalar { }
class Date_2 extends date { }
class DateTime extends date { }
export const db: DatabaseService;
/**
* Shortcut to `cds.log(...).debug`, returning `undefined` if `cds.log(...)._debug` is `false`.
* Use like this:
* @example
* ```js
* const dbg = cds.debug('foo')
* ...
* dbg && dbg('message')
* ```
*
* @param name - logger name
*/
export function debug (name: string): undefined | Log
class Decimal extends Float {
precision?: number
scale?: number
}
/**
* @beta helper
*/
type DeepPartial<T> = T extends object
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
? T extends Function
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: { [K in keyof T]?: DeepPartial<T[K]> }
: T
/**
* Definitions are the central elements of a CDS model.
*/
type Definition = context_2 & service_2 & type_2 & struct_2 & entity_2 & Association_2
type Definition_2 = any_
/**
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#iterable)
*/
type Definitions<T extends any_ = any_> = IterableMap<T>
const delete_: Service['delete'];
export { delete_ as delete };
type DELETE_2 = { DELETE: {
from: ref | name,
where?: predicate,
}, }
export { DELETE_2 as DELETE }
interface DELETE_3<T> extends Where<T>, And, ByKey {}
class DELETE_3<T> extends ConstructedQuery<T> {
private constructor();
static from:
TaggedTemplateQueryPart<Awaitable<SELECT_3<unknown>, InstanceType<StaticAny>>>
& (<T>(entity: EntityDescription | ArrayConstructable, primaryKey?: PK) => DELETE_3<T>)
& ((subject: ref) => DELETE_3<_TODO_2>)
DELETE: CQN.DELETE['DELETE']
}
class Double extends Float { }
type DROP_2 = { DROP: {
entity: name,
table: ref,
view: ref,
}, }
export { DROP_2 as DROP }
class DROP_3<T> extends ConstructedQuery<T> {
private constructor();
static entity (entity: EntityDescription): DROP_3<EntityDescription>
DROP: CQN.DROP['DROP']
}
export type EDM = { $version: string }
export type EDMX = XML
type Element = type_2 & struct_2 & Association_2
export const entities: Service['entities'];
/**
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#cds-entity)
*/
export interface entity extends Omit<csn.entity, 'elements' | 'items' | 'keys' | 'drafts'> {}
export class entity extends struct<'entity'> {
is_entity: true
keys: Definitions<type>
associations: Definitions<Association>
compositions: Definitions<Composition>
actions: Definitions<action>
texts?: entity
drafts?: entity
}
interface entity_2 extends Omit<struct_2, 'elements'> {
/**
* Entities with a query signify a view
*/
query?: SELECT_2
/**
* Elements of entities may have additional qualifiers
*/
elements: EntityElements
// REVISIT: following should move to LinkedCSN
keys: { [name: string]: Definition }
drafts?: entity_2
}
type EntityDescription = entity | Definition | string
type EntityElements = {
[name: string]: Element & {
key?: boolean,
virtual?: boolean,
unique?: boolean,
notNull?: boolean,
precision?: number,
scale?: number,
length?: number,
},
}
type Entries<T = any> = {[key:string]: T} | {[key:string]: T}
export type enum_literal = { '#': string }
/**
* Access to the configuration for Node.js runtime and tools.
* The object is the effective result of configuration merged from various sources,
* filtered through the currently active profiles, thus highly dependent on the current working
* directory and process environment.
*/
export const env: {
build: _TODO,
hana: _TODO,
i18n: {
languages: string[],
default_language: string,
folders: string[],
[key: string]: any,
},
profiles: string[],
log: {
user: boolean,
levels: Record<string, Lowercase<keyof typeof levels>>,
als_custom_fields: Record<string, number>,
cls_custom_fields: string[],
},
requires: env.Requires,
folders: {
app: string,
db: string,
srv: string,
fts: string,
[key: string]: string, // to allow additional values
},
odata: _TODO,
query: _TODO,
sql: _TODO,
} & { [key: string]: any };
export namespace env {
export interface MockUser {
tenant?: string
roles?: string[]
features?: string[]
}
export interface MockUsers {
alice: MockUser
bob: MockUser
carol: MockUser
dave: MockUser
erin: MockUser
fred: MockUser
[key: string]: MockUser | undefined
}
export type Requires = {
auth: {
kind: 'dummy' | 'mocked' | 'basic' | 'xsuaa' | 'ias' | string,
impl: string,
users?: MockUsers,
tenants?: {
[key: string]: {
features?: string[],
},
},
credentials?: Credentials,
binding?: Binding,
[key: string]: any,
},
db: {
kind: 'hana' | 'sqlite' | 'sql' | string,
binding?: Binding,
[key: string]: any,
},
multitenancy?: boolean | { kind: string, jobs: {
clusterSize: number,
workerSize: number,
t0: string,
[key: string]: any,
},},
toggles?: boolean,
extensibility?: boolean | {
model: string[],
tenantCheckInterval: number,
[key: string]: any,
},
messaging?: {
kind: 'file-based-messaging' | 'redis-messaging' | 'local-messaging' | 'enterprise-messaging' | 'enterprise-messaging-shared' | string,
format: 'cloudevents' | string,
[key: string]: any,
},
'cds.xt.SaasProvisioningService'?: {
model: string,
kind: string,
alwaysUpgradeModel?: boolean,
[key: string]: any,
},
'cds.xt.SmsProvisioningService'?: {
model: string,
kind: string,
[key: string]: any,
},
'cds.xt.ExtensibilityService'?: {
model: string,
kind?: string,
[key: string]: any,
},
'cds.xt.ModelProviderService'?: {
model: string,
root: string,
kind?: string,
[key: string]: any,
},
'cds.xt.DeploymentService'?: {
model: string,
kind?: string,
[key: string]: any,
},
[key: string]: any,
}
export type Binding = {
type: 'cf' | 'k8s' | string,
apiEndpoint?: string,
org?: string,
space?: string,
instance?: string,
key?: string,
}
export type Credentials = {
clientid?: string,
clientsecret?: string,
url?: string,
xsappname?: string,
certurl?: string,
certificate?: string,
[key: string]: any,
}
}
export class event extends aspect<'event'> {}
/**
* @see [capire docs](https://cap.cloud.sap/docs/node.js/events)
*/
class Event_2<T = unknown> extends EventContext {
event: string
data: T
headers: any
before(phase: 'commit', handler: () => void)
on(phase: 'succeeded' | 'failed' | 'done', handler: () => void)
}
export { Event_2 as Event }
/**
* Represents the invocation context of incoming request and event messages.
* @see [capire docs](https://cap.cloud.sap/docs/node.js/events)
*/
export class EventContext {
constructor (properties: { event: string, data?: object, query?: object, headers?: object })
http?: { req: import('express').Request, res: import('express').Response }
tenant: string
user: User
id: string
locale: `${string}_${string}`
timestamp: Date
features?: { [key: string]: boolean }
model: LinkedCSN
}
export interface EventHandler {
// (msg : types.EventMessage) : Promise<any> | any | void
(req: Request_2): Promise<any> | any | void
}
/**
* Provides a graceful shutdown for running servers, by first emitting `cds.emit('shutdown')`.
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-facade#cds-exit)
*/
export function exit (): void
export type expr = ref | val | xpr | function_call | SELECT_2
export type expr_literal = { '=': string }
type Expression<E extends string | number | bigint | boolean> = `${E}${WS}${Op}${WS}`
type Expressions<L,E> = KVPairs<L, Expression<Exclude<keyof E, symbol>>, ColumnValue> extends true
? L
// fallback: allow for any string. Important for when user renamed properties
: KVPairs<L, Expression<string>, ColumnValue> extends true
? L
: never
/**
* Add aspects to a given object, for example:
*
* @example
* ```js
* extend (Object.prototype) .with (class {
* get foo() { return ... }
* bar() {...}
* }.prototype)
* ```
*/
export function extend<T> (target: T): {
with<E extends readonly any[]>(...ext: E): T & Intersect<E>,
}
/**
* Extensions capture `extend Foo with { ... }` directives.
*/
type Extension = {
extend: FQN,
elements?: { [name: string]: Element },
includes?: FQN[],
}
export type filename = string
type Filter = string | (<T extends any_ = any_>(def: T) => boolean)
export type _flavor = 'parsed' | 'xtended' | 'inferred'
class Float extends number { }
export type FluentScheduling<O extends keyof FluentScheduling = never> = {
after: <T = any>(t: number | string, u?: string) => Promise<T> & Omit<FluentScheduling<O | 'after'>, O | 'after'>,
every: <T = any>(t: number | string, u?: string) => Promise<T> & Omit<FluentScheduling<O | 'every'>, O | 'every'>,
}
export const foreach: Service['foreach'];
type Formatter = {
/**
* Custom format function
*
* @param module - logger name
* @param level - log level
* @param args - additional arguments
* @returns an array of arguments, which are passed to the logger (for example, `console.log()`)
*/
(module: string, level: number, args: any[]): any[],
}
/**
* The fully-quality name of a definition.
*/
type FQN = string
/** @private */
export type function_call = { func: string, args: { [key: string]: any }[] }
/**
* Loads and parses models from the specified files.
* Uses `cds.resolve` to fetch the respective models.
* Essentially a shortcut for `cds.compile.to.csn(files)`
* @param files - filenames of models or if folder containing models
*/
export function get (files: '*' | filename | filename[], o?: _options): Promise<csn.CSN>
interface GroupBy {
groupBy: TaggedTemplateQueryPart<this>
& ((columns: Partial<{[column in KeyOfTarget<this extends ConstructedQuery<infer E> ? E : never, never>]: any}>) => this)
& ((...expr: string[]) => this)
& ((ref: ref) => this)
// columns currently not being auto-completed due to complexity
}
/**
* Types herein can be used to type handler functions that are not declared in line:
* @example
* ```ts
* import { myAction } from '#cds-models/myService'
*
* function onMyFunction (req: HandlerFunction<typeof myAction>['parameters']['req']): HandlerFunction<typeof myAction>['returns'] {
* ...
* }
*
* srv.on(myAction, onMyFunction)
* ```
*/
export type HandlerFunction<F extends CdsFunction> = {
parameters: {
/** @beta helper */
req: Request_2<F['__parameters']>,
},
/** @beta helper */
returns: F['__returns'],
}
interface Having<T> {
having: HavingWhere<this, T>
}
type HavingWhere<This, E> =
/**
* @param predicate - An object with keys that are valid fields of the target entity and values that are compared to the respective fields.
* @example
* ```js
* SELECT.from(Books).where({ ID: 42 }) // where ID is a valid field of Book
* SELECT.from(Books).having({ ID: 42 }) // where ID is a valid field of Book
* ```
*/
((predicate: Partial<{[column in KeyOfTarget<This extends ConstructedQuery<infer E> ? E : never, never>]: any}>) => This)
/**
* @param expr - An array of expressions, where every odd element is a valid field of the target entity and every even element is a value that is compared to the respective field.
* @example
* ```js
* SELECT.from(Books).where(['ID =', 42 ]) // where ID is a valid, numerical field of Book
* SELECT.from(Books).having(['ID =', 42 ]) // where ID is a valid, numerical field of Book
*```
*/
& (<const L extends unknown[]>(...expr: Expressions<L, UnwrappedInstanceType<E>>) => This)
& ((...expr: string[]) => This)
& TaggedTemplateQueryPart<This>
interface Hints {
hints: ((...hints: string[]) => this)
& ((hints: string[]) => this)
}
export const home: string;
export const i18n: I18nFacade;
export class I18nBundle {
constructor(options: I18nFilesOptions)
for(key: number | string | object, locale?: string | object, args?: object): string | undefined
at(key: number | string | object, locale?: string | object, args?: object): string | undefined
files: I18nFiles
get defaults(): Record<string, string>
get fallback(): Record<string, string>
key4(definition: entity): string
texts4 (locale: string): Texts
translations4 (...locales : string[]) : { [locale: string]: Texts }
translations4 (locale : 'all' ) : { [locale: string]: Texts }
all () : Record<string, Texts>
}
export interface I18nFacade {
Bundle: typeof I18nBundle
Facade: I18nFacade
Files: typeof I18nFiles
get file(): string
get folders(): string[]
get labels(): I18nBundle
get messages(): I18nBundle
bundle4 (file: string, options?: I18nFilesOptions): I18nBundle
bundle4 (model: csn.CSN): I18nBundle
}
export class I18nFiles {
constructor (options: I18nFilesOptions)
get options(): I18nFilesOptions
get basename(): string
content4(locale: string, suffix: string): Array<object>
}
export interface I18nFilesOptions {
file? : string
model? : csn.CSN
roots? : string[]
leafs? : string[]
folders? : string[]
}
export const insert: Service['insert'];
type INSERT_2 = { INSERT: {
into: ref | name,
entries: data[],
columns: string[],
values: primitive[],
rows: primitive[][],
from: SELECT_2,
}, }
export { INSERT_2 as INSERT }
interface INSERT_3<T> extends Columns<T>, InUpsert<T> {}
class INSERT_3<T> extends ConstructedQuery<T> {
private constructor();
static into: (<T extends ArrayConstructable> (entity: T, ...entries: DeepPartial<SingularInstanceType<T>>[]) => INSERT_3<SingularInstanceType<T>>)
& (<T extends ArrayConstructable> (entity: T, entries?: DeepPartial<SingularInstanceType<T>>[]) => INSERT_3<SingularInstanceType<T>>)
& (TaggedTemplateQueryPart<INSERT_3<unknown>>)
& ((entity: EntityDescription, ...entries: Entries[]) => INSERT_3<StaticAny>)
& ((entity: EntityDescription, entries?: Entries) => INSERT_3<StaticAny>)
& (<T> (entity: Constructable<T>, ...entries: DeepPartial<T>[]) => INSERT_3<T>)
& (<T> (entity: Constructable<T>, entries?: DeepPartial<T>[]) => INSERT_3<T>)
from (select: SELECT_3<T>): this
INSERT: CQN.INSERT['INSERT']
}
class Int16 extends Integer { }
class Int32 extends Integer { }
class Int64 extends Integer { }
class Integer extends number { }
type Intersect<T extends readonly unknown[]> = T extends [infer Head, ...infer Tail]
? Head & Intersect<Tail>
: unknown
interface InUpsert<T> {
data (block: (e: T) => void): this
entries (...entries: DeepPartial<T>[]): this
entries (entries: DeepPartial<T>[]): this
values (...val: (null | Primitive)[]): this
values (val: (null | Primitive)[]): this
rows (...row: (null | Primitive)[][]): this
rows (row: (null | Primitive)[][]): this
into: (<T extends ArrayConstructable> (entity: T) => this)
& TaggedTemplateQueryPart<this>
& ((entity: EntityDescription) => this)
}
/**
* Object structure that exposes both array-like and object-like behaviour.
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#iterable)
*/
type IterableMap<T> = { [name: string]: T } & Iterable<T>
type JSON_2 = string
export { JSON_2 as JSON }
export type Key = number | string | any
type KeyOfSingular<T> = Unwrap<T> extends T
? keyof T
: keyof Unwrap<T>
type KeyOfTarget<T, F = string | column_expr> = T extends ConstructedQuery<infer U>
? (U extends ArrayConstructable // Books
? keyof SingularInstanceType<U>
: U extends Constructable // Book
? keyof InstanceType<U>
: F)
: F
type kinds = 'aspect' | 'entity' | 'type' | 'event' | 'action' | 'function' | 'service' | 'context' | 'elements' | 'element'
/**
* T is a tuple of alternating K, V pairs -> true, else false
* Allows for variadic parameter lists with alternating expecing types,
* like we have in cql.SELECT.where
*/
type KVPairs<T,K,V> = T extends []
? true
: T extends [K, V, ...infer R]
? KVPairs<R,K,V>
: false
class LargeBinary extends Binary { }
class LargeString extends String_2 { }
/**
* @deprecated since version 8.1
*/
export function lazified<T> (target: T): T
/**
* @deprecated since version 8.1
*/
export function lazify<T> (target: T): T
enum levels {
// SILLY and VERBOSE are aliases for TRACE
/* eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values */
SILENT = 0, ERROR = 1, WARN = 2, INFO = 3, DEBUG = 4, TRACE = 5, SILLY = 5, VERBOSE = 5
}
interface Limit {
limit: TaggedTemplateQueryPart<this>
& ((rows: number, offset?: number) => this)
}
export const linked: {
/**
* Turns the given plain CSN model into a linked model
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect)
*/
(model: csn.CSN): linked_2.LinkedCSN,
/**
* Base classes of linked definitions from reflected models.
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#cds-builtin-classes)
*/
classes: typeof classes,
/**
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#linked-csn)
*/
LinkedCSN: linked_2.LinkedCSN,
/**
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#iterable)
*/
LinkedDefinitions: IterableMap<linked_2.classes.any_>,
};
export namespace linked {
export type LinkedDefinitions = IterableMap<linked_2.classes.any_>
export type LinkedCSN = linked_2.LinkedCSN
// synthetic class that is prominently featured in capire,
// but described as "accessible through cds.linked.classes.any"
export type LinkedDefinition = linked_2.classes.any_
export namespace classes {
export type type = __type
export type aspect = __aspect
export type any_ = __any_
export type scalar = __scalar
// can not shadow builtins. Same for string and number...
//export type boolean = LinkedClasses.Boolean // on purpose
export type Boolean = __Boolean
export type UUID = __UUID
//export type string = LinkedClasses.String // on purpose
export type String = __String
export type LargeString = __LargeString
export type Binary = __Binary
export type LargeBinary = __LargeBinary
export type Vector = __Vector
//export type number = LinkedClasses.scalar // currently no better way to do this
export type Integer = __Integer
export type UInt8 = __UInt8
export type Int16 = __Int16
export type Int32 = __Int32
export type Int64 = __Int64
export type Float = __Float
export type Double = __Double
export type Decimal = __Decimal
export type date = __date
export type Date = __Date
export type Time = __Time
export type DateTime = __DateTime
export type TimeStamp = __TimeStamp
export type array = __array
export type struct = __struct
export type context_ = __context_
export type service = __service
export type entity = __entity
export type Association = __Association
export type Composition = __Composition
}
}
namespace linked_2 {
export {
ModelPart,
Definition_2 as Definition,
LinkedCSN,
classes
}
}
interface LinkedCSN extends Omit<csn.CSN, 'definitions'> {
/**
* Fetches definitions matching the given filter, returning an iterator on them.
* @example
* ```js
* let m = cds.reflect (aParsedModel)
* for (let d of m.each('entity')) console.log (d.kind, d.name)
* let entities = [...m.each('entity')] //> capture all
* let entities = m.all('entity') //> equivalent shortcut
* ```
*/
each<T extends any_>(x: Filter, defs?: Definitions<T>): IterableIterator<T>
/**
* Fetches definitions matching the given filter, returning them in an array.
* Convenience shortcut for `[...reflect.each('entity')]`
*/
all<T extends any_>(x: Filter, defs?: Definitions<T>): T[]
/**
* Fetches definitions matching the given filter, returning the first match, if any.
* @example
* let service = model.find('service')
* @param x - the filter
* @param defs - the definitions to fetch in, default: `this.definitions`
*/
find<T extends any_>(x: Filter, defs?: Definitions<T>): T | undefined
/**
* Calls the visitor for each definition matching the given filter.
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#foreach)
*/
foreach(x: Filter, visitor: Visitor, defs?: Definitions): this
foreach(visitor: Visitor, defs?: Definitions): this
/**
* Same as foreach but recursively visits each element definition
* @see [capire](https://cap.cloud.sap/docs/node.js/cds-reflect#foreach)
*/
forall(x: Filter, visitor: Visitor, defs?: Definitions): this
forall(visitor: Visitor, defs?: Definitions): this
/**
* Fetches definitions declared as children of a given parent context or service.
* It fetches all definitions whose fully-qualified names start with the parent's name.
* Returns the found definitions as an object with the local names as keys.
* @example
* ```js
* let service = model.find ('service')
* let entities = m.childrenOf (service)
* ```
* @param parent - either the parent itself or its fully-qualified name
* @param filter - an optional filter to apply before picking a child
*/
childrenOf(parent: any | string, filter?: ((def: any_) => boolean)): Definitions
/**
* Provides convenient access to the model's top-level definitions.
* For example, you can use it in an es6-import-like fashion to avoid
* working with fully-qualified names as follows:
*
* @example
* ```js
* let model = cds.reflect (cds.parse(`
* namespace our.lovely.bookshop;
* entity Books {...}
* entity Authors {...}
* `))
* const {Books,Authors} = model.exports
* SELECT.from (Books) .where ({ID:11})
* ```
*/
exports: IterableMap<any_>
definitions: IterableMap<any_>
entities: ModelPart<entity>
services: ModelPart<service_>
}
/**
* Shortcut for `cds.get(files, 'inferred')`
* @param files - filenames of models or if folder containing models
*/
export function load (files: '*' | filename | filename[], o?: _options): Promise<csn.CSN>
type Log = {
/**
* Logs a message
*
* @param message - text to log
* @param optionalParams - additional parameters, same as in `console.log(text, param1, ...)`
*/
(message?: any, ...optionalParams: any[]): void,
}
/**
* Create a new logger, or install a custom log formatter
*/
export const