@openmeter/sdk 1.0.0-beta.2 → 1.0.0-beta.22

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/package.json CHANGED
@@ -1,54 +1,58 @@
1
1
  {
2
- "name": "@openmeter/sdk",
3
- "version": "1.0.0-beta.2",
4
- "description": "Client for OpenMeter: Real-Time and Scalable Usage Metering",
5
- "license": "Apache 2.0",
6
- "homepage": "https://openmeter.io",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/openmeterio/openmeter.git",
10
- "directory": "api/client/node"
11
- },
12
- "main": "./dist/index.js",
13
- "types": "./dist/index.d.ts",
14
- "type": "module",
15
- "engines": {
16
- "node": ">=18.16.1"
17
- },
18
- "scripts": {
19
- "lint": "eslint . --ext .ts --format=pretty",
20
- "format": "prettier --write .",
21
- "build": "rimraf ./dist && tsc --build",
22
- "generate": "rimraf ./schemas && openapi-typescript \"../../openapi.yaml\" --output schemas/",
23
- "pretest": "npm run build",
24
- "test": "vitest --run --threads=false",
25
- "test:watch": "vitest --watch --threads=false",
26
- "prepublishOnly": "npm run generate && npm run build && npm run test && npm run lint"
27
- },
28
- "devDependencies": {
29
- "@types/node": "^20.5.0",
30
- "@types/node-fetch": "^2.6.4",
31
- "@typescript-eslint/eslint-plugin": "^6.4.0",
32
- "@typescript-eslint/parser": "^6.4.0",
33
- "eslint": "^8.47.0",
34
- "eslint-config-prettier": "^9.0.0",
35
- "eslint-formatter-pretty": "^5.0.0",
36
- "eslint-import-resolver-typescript": "^3.6.0",
37
- "eslint-plugin-compat": "^4.1.4",
38
- "eslint-plugin-import": "^2.28.0",
39
- "eslint-plugin-require-extensions": "^0.1.3",
40
- "eslint-plugin-unused-imports": "^3.0.0",
41
- "eslint-plugin-vitest": "^0.2.8",
42
- "openapi-typescript": "^6.5.0",
43
- "prettier": "^3.0.1",
44
- "rimraf": "^5.0.1",
45
- "typescript": "^5.1.6",
46
- "vitest": "^0.34.1"
47
- },
48
- "browserslist": [
49
- "current node"
50
- ],
51
- "dependencies": {
52
- "undici": "^5.23.0"
53
- }
54
- }
2
+ "name": "@openmeter/sdk",
3
+ "version": "1.0.0-beta.22",
4
+ "description": "Client for OpenMeter: Real-Time and Scalable Usage Metering",
5
+ "license": "Apache 2.0",
6
+ "homepage": "https://openmeter.io",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/openmeterio/openmeter.git",
10
+ "directory": "api/client/node"
11
+ },
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=18.16.1"
17
+ },
18
+ "scripts": {
19
+ "lint": "eslint . --ext .ts --format=pretty",
20
+ "format": "prettier --write .",
21
+ "build": "rimraf ./dist && tsc --build",
22
+ "generate": "rimraf ./schemas && openapi-typescript '../../openapi.yaml' --output schemas/openapi.ts && prettier --write schemas/",
23
+ "pretest": "npm run build",
24
+ "test": "vitest --run --threads=false",
25
+ "test:watch": "vitest --watch --threads=false",
26
+ "prepublishOnly": "npm run generate && npm run build && npm run test && npm run lint"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^20.8.9",
30
+ "@types/node-fetch": "2.6.7",
31
+ "@typescript-eslint/eslint-plugin": "6.9.0",
32
+ "@typescript-eslint/parser": "6.9.0",
33
+ "eslint": "8.52.0",
34
+ "eslint-config-prettier": "9.0.0",
35
+ "eslint-formatter-pretty": "5.0.0",
36
+ "eslint-import-resolver-typescript": "3.6.1",
37
+ "eslint-plugin-compat": "4.2.0",
38
+ "eslint-plugin-import": "2.29.0",
39
+ "eslint-plugin-require-extensions": "0.1.3",
40
+ "eslint-plugin-unused-imports": "3.0.0",
41
+ "eslint-plugin-vitest": "0.3.2",
42
+ "openapi-typescript": "6.7.0",
43
+ "prettier": "3.0.3",
44
+ "rimraf": "5.0.5",
45
+ "typescript": "5.2.2",
46
+ "vitest": "0.34.6"
47
+ },
48
+ "browserslist": [
49
+ "current node"
50
+ ],
51
+ "dependencies": {
52
+ "ai": "^2.2.19",
53
+ "undici": "^5.27.0"
54
+ },
55
+ "optionalDependencies": {
56
+ "js-tiktoken": "^1.0.7"
57
+ }
58
+ }
package/clients/client.ts DELETED
@@ -1,153 +0,0 @@
1
- import { IncomingHttpHeaders } from 'http'
2
- import { Dispatcher, request } from 'undici'
3
- import { components } from '../schemas/openapi.js'
4
-
5
- export type OpenMeterConfig = {
6
- baseUrl: string
7
- token?: string
8
- username?: string
9
- password?: string
10
- headers?: IncomingHttpHeaders
11
- }
12
-
13
- export type RequestOptions = {
14
- headers?: IncomingHttpHeaders
15
- }
16
-
17
- export type Problem = components['schemas']['Problem']
18
-
19
- type UndiciRequestOptions = { dispatcher?: Dispatcher } & Omit<Dispatcher.RequestOptions, 'origin' | 'path' | 'method'> & Partial<Pick<Dispatcher.RequestOptions, 'method'>>
20
-
21
- export class BaseClient {
22
- protected config: OpenMeterConfig
23
-
24
- constructor(config: OpenMeterConfig) {
25
- this.config = config
26
- }
27
-
28
- protected async request<T>({
29
- path,
30
- method,
31
- searchParams,
32
- headers,
33
- body,
34
- options
35
- }: {
36
- path: string
37
- method: Dispatcher.HttpMethod,
38
- searchParams?: URLSearchParams,
39
- headers?: IncomingHttpHeaders,
40
- body?: string | Buffer | Uint8Array,
41
- options?: RequestOptions
42
- }): Promise<T> {
43
- // Building URL
44
- const url = this.getUrl(path, searchParams)
45
-
46
- // Request options
47
- const reqHeaders: IncomingHttpHeaders = {
48
- Accept: 'application/json',
49
- ...headers,
50
- ...this.getAuthHeaders(),
51
- ...this.config.headers,
52
- ...options?.headers,
53
- }
54
- const reqOpts: UndiciRequestOptions = {
55
- method,
56
- headers: reqHeaders
57
- }
58
-
59
- // Optional body
60
- if (body) {
61
- if (!reqHeaders['Content-Type'] && !reqHeaders['content-type']) {
62
- throw new Error('Content Type is required with body')
63
- }
64
-
65
- reqOpts.body = body
66
- }
67
-
68
- const resp = await request(url, reqOpts)
69
-
70
- // Error handling
71
- if (resp.statusCode > 399) {
72
- if (resp.headers['content-type'] === 'application/problem+json') {
73
- const problem = await resp.body.json() as Problem
74
- throw new HttpError({
75
- statusCode: resp.statusCode,
76
- problem,
77
- })
78
- }
79
-
80
- // Requests can fail before API, in this case we only have a status code
81
- throw new HttpError({
82
- statusCode: resp.statusCode,
83
- })
84
- }
85
-
86
- // Response parsing
87
- if (resp.statusCode === 204) {
88
- return undefined as unknown as T
89
- }
90
- if (resp.headers['content-type'] === 'application/json') {
91
- return await resp.body.json() as T
92
- }
93
- if (!resp.headers['content-type']) {
94
- throw new Error('Missing content type')
95
- }
96
-
97
- throw new Error(`Unknown content type: ${resp.headers['content-type']}`)
98
- }
99
-
100
- protected getUrl(path: string, searchParams?: URLSearchParams) {
101
- let qs = searchParams ? searchParams.toString() : ''
102
- qs = qs.length > 0 ? `?${qs}` : ''
103
- const url = new URL(`${path}${qs}`, this.config.baseUrl)
104
- return url
105
- }
106
-
107
- protected getAuthHeaders(): IncomingHttpHeaders {
108
- if (this.config.token) {
109
- return {
110
- authorization: `Bearer ${this.config.token} `,
111
- }
112
- }
113
-
114
- if (this.config.username && this.config.password) {
115
- const encoded = Buffer.from(
116
- `${this.config.username}:${this.config.password} `
117
- ).toString('base64')
118
- return {
119
- authorization: `Basic ${encoded} `,
120
- }
121
- }
122
-
123
- return {}
124
- }
125
-
126
- protected static toURLSearchParams(params: Record<string, string | number | Date | string[]>): URLSearchParams {
127
- const searchParams = new URLSearchParams()
128
-
129
- for (const [key, value] of Object.entries(params)) {
130
- if (Array.isArray(value)) {
131
- searchParams.append(key, value.join(','))
132
- } else if (value instanceof Date) {
133
- searchParams.append(key, value.toISOString())
134
- } else {
135
- searchParams.append(key, value.toString())
136
- }
137
- }
138
-
139
- return searchParams
140
- }
141
- }
142
-
143
- export class HttpError extends Error {
144
- public statusCode: number
145
- public problem?: Problem
146
-
147
- constructor({ statusCode, problem }: { statusCode: number; problem?: Problem }) {
148
- super(problem?.type || 'unexpected status code')
149
- this.name = 'HttpError'
150
- this.statusCode = statusCode
151
- this.problem = problem
152
- }
153
- }
package/clients/event.ts DELETED
@@ -1,109 +0,0 @@
1
- import crypto from 'crypto'
2
- import { components } from '../schemas/openapi.js'
3
- import { RequestOptions, BaseClient, OpenMeterConfig } from './client.js'
4
-
5
- // We export Event instead
6
- type CloudEvents = components['schemas']['Event']
7
-
8
- /**
9
- * Usage Event
10
- */
11
- export type Event = {
12
- /**
13
- * @description The version of the CloudEvents specification which the event uses.
14
- * @example 1.0
15
- */
16
- specversion?: string
17
- /**
18
- * @description Unique identifier for the event, defaults to uuid v4.
19
- * @example "5c10fade-1c9e-4d6c-8275-c52c36731d3c"
20
- */
21
- id?: string
22
- /**
23
- * Format: uri-reference
24
- * @description Identifies the context in which an event happened, defaults to: @openmeter/sdk
25
- * @example services/service-0
26
- */
27
- source?: string
28
- /**
29
- * @description Describes the type of event related to the originating occurrence.
30
- * @example "api_request"
31
- */
32
- type: string
33
- /**
34
- * @description Describes the subject of the event in the context of the event producer (identified by source).
35
- * @example "customer_id"
36
- */
37
- subject: string
38
- /**
39
- * Format: date-time
40
- * @description Date of when the occurrence happened.
41
- * @example new Date('2023-01-01T01:01:01.001Z')
42
- */
43
- time?: Date
44
- /**
45
- * Format: uri
46
- * @description Identifies the schema that data adheres to.
47
- */
48
- dataschema?: string
49
- /**
50
- * @description Content type of the data value. Must adhere to RFC 2046 format.
51
- * @example application/json
52
- * @enum {string|null}
53
- */
54
- datacontenttype?: 'application/json'
55
- /**
56
- * @description The event payload.
57
- * @example {
58
- * "duration_ms": "12",
59
- * "path": "/hello"
60
- * }
61
- */
62
- data: Record<string, string | number | Record<string, string | number>>
63
- }
64
-
65
- export class EventsClient extends BaseClient {
66
- constructor(config: OpenMeterConfig) {
67
- super(config)
68
- }
69
-
70
- /**
71
- * Ingest usage event in a CloudEvents format
72
- * @see https://cloudevents.io
73
- */
74
- public async ingest(
75
- usageEvent: Event,
76
- options?: RequestOptions
77
- ): Promise<void> {
78
- if (usageEvent.datacontenttype && usageEvent.datacontenttype !== 'application/json') {
79
- throw new TypeError(
80
- `Unsupported datacontenttype: ${usageEvent.datacontenttype}`
81
- )
82
- }
83
-
84
- // We default where we can to lower the barrier to use CloudEvents
85
- const body: CloudEvents = {
86
- specversion: usageEvent.specversion ?? '1.0',
87
- id: usageEvent.id ?? crypto.randomUUID(),
88
- source: usageEvent.source ?? '@openmeter/sdk',
89
- type: usageEvent.type,
90
- subject: usageEvent.subject,
91
- time: usageEvent.time?.toISOString(),
92
- datacontenttype: usageEvent.datacontenttype,
93
- dataschema: usageEvent.dataschema,
94
- data: usageEvent.data
95
- }
96
-
97
- // Making Request
98
- return await this.request({
99
- path: '/api/v1/events',
100
- method: 'POST',
101
- body: JSON.stringify(body),
102
- headers: {
103
- 'Content-Type': 'application/cloudevents+json',
104
- },
105
- options
106
- })
107
- }
108
- }
109
-
package/clients/meter.ts DELETED
@@ -1,84 +0,0 @@
1
- import { paths, components } from '../schemas/openapi.js'
2
- import { BaseClient, OpenMeterConfig, RequestOptions } from './client.js'
3
-
4
- export enum WindowSize {
5
- MINUTE = 'MINUTE',
6
- HOUR = 'HOUR',
7
- DAY = 'DAY'
8
- }
9
-
10
- export enum MeterAggregation {
11
- SUM = 'SUM',
12
- COUNT = 'COUNT',
13
- AVG = 'AVG',
14
- MIN = 'MIN',
15
- MAX = 'MAX',
16
- }
17
-
18
- export type MeterQueryParams = {
19
- subject?: string
20
- /**
21
- * @description Start date.
22
- * Must be aligned with the window size.
23
- * Inclusive.
24
- */
25
- from?: Date
26
- /**
27
- * @description End date.
28
- * Must be aligned with the window size.
29
- * Inclusive.
30
- */
31
- to?: Date
32
- /** @description If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. */
33
- windowSize?: WindowSizeType
34
- /** @description If not specified a single aggregate will be returned for each subject and time window. */
35
- groupBy?: string[]
36
- }
37
-
38
- export type MeterQueryResponse = paths['/api/v1/meters/{meterIdOrSlug}/values']['get']['responses']['200']['content']['application/json']
39
-
40
- export type MeterValue = components['schemas']['MeterValue']
41
- export type Meter = components['schemas']['Meter']
42
- export type WindowSizeType = components['schemas']['WindowSize']
43
-
44
- export class MetersClient extends BaseClient {
45
- constructor(config: OpenMeterConfig) {
46
- super(config)
47
- }
48
-
49
- /**
50
- * Get one meter by slug
51
- */
52
- public async get(slug: string, options?: RequestOptions): Promise<Meter> {
53
- return this.request<Meter>({
54
- method: 'GET',
55
- path: `/api/v1/meters/${slug}`,
56
- options,
57
- })
58
- }
59
-
60
- /**
61
- * List meters
62
- */
63
- public async list(options?: RequestOptions): Promise<Meter[]> {
64
- return this.request<Meter[]>({
65
- method: 'GET',
66
- path: `/api/v1/meters`,
67
- options,
68
- })
69
- }
70
-
71
- /**
72
- * Get aggregated values of a meter
73
- */
74
- public async values(slug: string, params?: MeterQueryParams, options?: RequestOptions): Promise<MeterQueryResponse> {
75
- const searchParams = params ? BaseClient.toURLSearchParams(params) : undefined
76
- return this.request<MeterQueryResponse>({
77
- method: 'GET',
78
- path: `/api/v1/meters/${slug}/values`,
79
- searchParams,
80
- options,
81
- })
82
- }
83
- }
84
-