Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
676 changes: 591 additions & 85 deletions integrations/dsh/plugins/powercontext/lib/index.js

Large diffs are not rendered by default.

609 changes: 608 additions & 1 deletion integrations/dsh/plugins/powercontext/openapi/powercontext.yaml

Large diffs are not rendered by default.

32 changes: 30 additions & 2 deletions integrations/dsh/plugins/powercontext/scripts/openapi-ops.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,27 @@ function requestLocation(bodySchema, parameters) {

function operationHasScope(doc, bodySchema, parameters) {
if (bodySchema && schemaHasScope(doc, bodySchema)) return true
return parameters.some((parameter) => parameter.in === 'query' && parameter.name === 'scope_id')
return parameters.some((parameter) => ['path', 'query'].includes(parameter.in) && parameter.name === 'scope_id')
}

function parameterNames(parameters, location) {
return parameters
.filter((parameter) => parameter.in === location && typeof parameter.name === 'string')
.map((parameter) => parameter.name)
}

function responseStatuses(doc, operation) {
const successStatuses = []
const emptyStatuses = []
for (const [rawStatus, response] of Object.entries(operation.responses ?? {})) {
if (!/^\d+$/.test(rawStatus)) continue
const status = Number(rawStatus)
if (!((status >= 200 && status < 300) || status === 304)) continue
successStatuses.push(status)
const resolved = deref(doc, response)
if (!resolved?.content || Object.keys(resolved.content).length === 0) emptyStatuses.push(status)
}
return { successStatuses, emptyStatuses }
}

export function parseOperations(doc) {
Expand All @@ -78,12 +98,17 @@ export function parseOperations(doc) {
if (!operation?.operationId) continue
const parameters = operationParameters(doc, pathItem, operation)
const bodySchema = jsonBodySchema(doc, operation)
const statuses = responseStatuses(doc, operation)
rows.push({
operationId: operation.operationId,
method: method.toUpperCase(),
path,
location: requestLocation(bodySchema, parameters),
scope: operationHasScope(doc, bodySchema, parameters),
pathParams: parameterNames(parameters, 'path'),
queryParams: parameterNames(parameters, 'query'),
headerParams: parameterNames(parameters, 'header'),
...statuses,
})
}
}
Expand All @@ -94,7 +119,10 @@ export function renderOperationsSource(rows) {
const body = rows
.map((row) => {
const location = row.location === null ? 'null' : `"${row.location}"`
return ` ${row.operationId}: { method: '${row.method}', path: '${row.path}', location: ${location}, scope: ${row.scope} },`
const pathParams = JSON.stringify(row.pathParams).replaceAll('"', "'")
const queryParams = JSON.stringify(row.queryParams).replaceAll('"', "'")
const headerParams = JSON.stringify(row.headerParams).replaceAll('"', "'")
return ` ${row.operationId}: { method: '${row.method}', path: '${row.path}', location: ${location}, scope: ${row.scope}, pathParams: ${pathParams}, queryParams: ${queryParams}, headerParams: ${headerParams}, successStatuses: ${JSON.stringify(row.successStatuses)}, emptyStatuses: ${JSON.stringify(row.emptyStatuses)} },`
})
.join('\n')
return `/*
Expand Down
83 changes: 71 additions & 12 deletions integrations/dsh/plugins/powercontext/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,62 @@ function queryString(payload: JsonObject | undefined): string {
return encoded ? `?${encoded}` : ''
}

interface PreparedRequest {
path: string
query: string
headers: Record<string, string>
body: JsonObject | undefined
}

function encodePathSegment(value: unknown): string {
return encodeURIComponent(String(value)).replace(/[!'()*]/g, (character) => (
`%${character.charCodeAt(0).toString(16).toUpperCase()}`
))
}

function headerPayloadKey(name: string): string {
return name.toLowerCase().replaceAll('-', '_')
}

function prepareRequest(spec: OperationSpec, payload: JsonObject | undefined): PreparedRequest {
const remaining = { ...(payload ?? {}) }
let path = spec.path as string
for (const name of spec.pathParams as readonly string[]) {
const value = remaining[name]
if (value === undefined || value === null) {
throw new TypeError(`${spec.method} ${spec.path} requires ${name}`)
}
path = path.replace(`{${name}}`, encodePathSegment(value))
delete remaining[name]
}

const headers: Record<string, string> = {}
for (const name of spec.headerParams as readonly string[]) {
const alias = headerPayloadKey(name)
const value = remaining[name] ?? remaining[alias]
delete remaining[name]
delete remaining[alias]
if (value !== undefined && value !== null) headers[name] = String(value)
}

const queryPayload: JsonObject = {}
for (const name of spec.queryParams as readonly string[]) {
const value = remaining[name]
delete remaining[name]
if (value !== undefined && value !== null) queryPayload[name] = value
}
return {
path,
query: queryString(queryPayload),
headers,
body: spec.location === 'body' ? remaining : undefined,
}
}

function hasStatus(statuses: readonly number[], status: number): boolean {
return statuses.includes(status)
}

function isRedirect(status: number): boolean {
return status >= 300 && status < 400
}
Expand All @@ -147,9 +203,10 @@ export class PowerContextClient {
): Promise<ClientSuccess> {
if (!(id in OPERATIONS)) throw new UnknownOperationError(id)
const spec = OPERATIONS[id as OperationId]
const url = this.buildUrl(spec, payload)
const prepared = prepareRequest(spec, payload)
const url = `${this.baseUrl}${prepared.path}${prepared.query}`
try {
const response = await this.fetchImpl(url, this.buildInit(spec, payload, signal))
const response = await this.fetchImpl(url, this.buildInit(spec, prepared, signal))
return await this.parseResponse(id, spec, payload, response)
} catch (error) {
if (error instanceof ServerResponseError || error instanceof InvalidResponseError) throw error
Expand All @@ -158,15 +215,11 @@ export class PowerContextClient {
}
}

private buildUrl(spec: OperationSpec, payload: JsonObject | undefined): string {
const suffix = spec.location === 'query' ? queryString(payload) : ''
return `${this.baseUrl}${spec.path}${suffix}`
}

private buildInit(spec: OperationSpec, payload: JsonObject | undefined, signal?: AbortSignal): RequestInit {
private buildInit(spec: OperationSpec, request: PreparedRequest, signal?: AbortSignal): RequestInit {
const headers: Record<string, string> = {
Accept: 'application/json',
'User-Agent': PLUGIN_USER_AGENT,
...request.headers,
}
if (this.authorization) headers.Authorization = this.authorization
const init: RequestInit = {
Expand All @@ -175,9 +228,9 @@ export class PowerContextClient {
redirect: 'manual',
signal: combineSignals([timeoutSignal(this.requestTimeoutMs), ...signal ? [signal] : []]),
}
if (spec.method === 'POST' && spec.location === 'body') {
if (spec.location === 'body') {
headers['Content-Type'] = 'application/json'
init.body = JSON.stringify(payload ?? {})
init.body = JSON.stringify(request.body ?? {})
}
return init
}
Expand All @@ -194,12 +247,18 @@ export class PowerContextClient {
payload: JsonObject | undefined,
response: Response,
): Promise<ClientSuccess> {
if (isRedirect(response.status)) throw new InvalidResponseError(spec.path)
const success = (response.status >= 200 && response.status < 300)
|| hasStatus(spec.successStatuses as readonly number[], response.status)
if (isRedirect(response.status) && !success) throw new InvalidResponseError(spec.path)
const bytes = await readLimitedBody(response)
const requestId = response.headers.get(REQUEST_ID_HEADER) ?? undefined
if (response.status < 200 || response.status >= 300) {
if (!success) {
throw this.httpError(response.status, spec.path, requestId, bytes)
}
if (hasStatus(spec.emptyStatuses as readonly number[], response.status)) {
if (bytes.byteLength !== 0) throw new InvalidResponseError(spec.path, requestId)
return { kind: 'json', value: null, status: response.status, requestId }
}
if (id === 'get_handoff_report' && payload?.download === true) {
return { kind: 'bytes', value: bytes, status: response.status, requestId }
}
Expand Down
Loading
Loading