repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
tony-aq/optic
|
workspaces/ui-v2/src/hooks/util/useRunOnKeypress.ts
|
<reponame>tony-aq/optic
import { KeyboardEvent, useCallback } from 'react';
export const useRunOnKeypress = <T extends (...args: any) => any>(
fn: T,
options: {
keys?: Set<string>;
inputTagNames?: Set<string>;
} = {}
) => {
return useCallback(
(e: KeyboardEvent) => {
const { keys, inputTagNames } = options;
// use upper case to handle case insensitivities
const upperCaseTags =
inputTagNames &&
new Set([...inputTagNames].map((tag) => tag.toUpperCase()));
const upperCaseKeys =
keys && new Set([...keys].map((key) => key.toUpperCase()));
const keyPressValid = upperCaseKeys
? upperCaseKeys.has(e.key.toUpperCase())
: true;
const elementTagValid = upperCaseTags
? e.target instanceof Element
? upperCaseTags.has(e.target.tagName.toUpperCase())
: false
: true;
if (keyPressValid && elementTagValid) {
fn(e);
}
},
[fn, options]
);
};
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/ReviewEndpointDiffPage/ReviewEndpointDiffPageContainer.tsx
|
import React, { FC } from 'react';
import { RouteComponentProps } from 'react-router';
import { LinearProgress } from '@material-ui/core';
import { useEndpointDiffs } from '<src>/pages/diffs/hooks/useEndpointDiffs';
import {
useNewBodyDiffInterpretations,
useShapeDiffInterpretations,
} from '<src>/pages/diffs/hooks/useDiffInterpretations';
import { useSharedDiffContext } from '<src>/pages/diffs/contexts/SharedDiffContext';
import { PageLayout } from '<src>/components';
import { DiffAccessoryNavigation } from '<src>/pages/diffs/components/DiffAccessoryNavigation';
import { useAppSelector, selectors } from '<src>/store';
import { ReviewEndpointDiffPage } from './ReviewEndpointDiffPage';
export const ReviewEndpointDiffContainer: FC<
RouteComponentProps<{
method: string;
pathId: string;
}>
> = ({ match }) => {
const { method, pathId } = match.params;
const endpointDiffs = useEndpointDiffs(pathId, method);
const endpoint = useAppSelector(selectors.getEndpoint({ pathId, method }));
const { context } = useSharedDiffContext();
const shapeDiffs = useShapeDiffInterpretations(
endpointDiffs.shapeDiffs,
context.results.trailValues
);
const newRegionDiffs = useNewBodyDiffInterpretations(
endpointDiffs.newRegionDiffs
);
return (
<PageLayout AccessoryNavigation={DiffAccessoryNavigation}>
{!endpoint || shapeDiffs.loading || newRegionDiffs.loading ? (
<LinearProgress variant="indeterminate" />
) : (
<ReviewEndpointDiffPage
endpoint={endpoint}
allDiffs={[...newRegionDiffs.results, ...shapeDiffs.results]}
method={method}
pathId={pathId}
/>
)}
</PageLayout>
);
};
|
tony-aq/optic
|
workspaces/optic-domain/src/shapes.ts
|
// Shape events
export enum ICoreShapeKinds {
ObjectKind = '$object',
ListKind = '$list',
MapKind = '$map',
OneOfKind = '$oneOf',
AnyKind = '$any',
StringKind = '$string',
NumberKind = '$number',
BooleanKind = '$boolean',
NullableKind = '$nullable',
OptionalKind = '$optional',
UnknownKind = '$unknown',
}
export enum ICoreShapeInnerParameterNames {
ListInner = '$listItem',
NullableInner = '$nullableInner',
OptionalInner = '$optionalInner',
}
// Optic engine shape types
export enum JsonType {
OBJECT = 'Object',
ARRAY = 'Array',
NULL = 'Null',
STRING = 'String',
NUMBER = 'Number',
BOOLEAN = 'Boolean',
UNDEFINED = 'Undefined',
}
// Matches optic-engine/src/projections/spectacle/shapes
export type FieldShape = {
name: string;
fieldId: string;
shapeId: string;
};
// Matches optic-engine/src/projections/spectacle/shapes
export type ShapeChoice =
| {
shapeId: string;
jsonType: JsonType.OBJECT;
fields: FieldShape[];
}
| {
shapeId: string;
jsonType: JsonType.ARRAY;
itemShapeId: string;
}
| {
shapeId: string;
jsonType: Exclude<JsonType, JsonType.OBJECT | JsonType.ARRAY>;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/store/documentationEdit/thunks.ts
|
<filename>workspaces/ui-v2/src/store/documentationEdit/thunks.ts
import { createAsyncThunk } from '@reduxjs/toolkit';
import { v4 as uuidv4 } from 'uuid';
import * as Sentry from '@sentry/react';
import { IForkableSpectacle } from '@useoptic/spectacle';
import {
AddContribution,
CQRSCommand,
JsonType,
PrunePathComponents,
} from '@useoptic/optic-domain';
import { SpectacleClient } from '<src>/clients';
import { RootState, AppDispatch } from '../root';
import { getValidContributions } from '../selectors';
const fetchRemoveEndpointCommands = async (
spectacle: IForkableSpectacle,
pathId: string,
method: string
): Promise<CQRSCommand[]> => {
const spectacleClient = new SpectacleClient(spectacle);
try {
return spectacleClient.fetchRemoveEndpointCommands(pathId, method);
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
};
const fetchFieldEditCommands = async (
spectacle: IForkableSpectacle,
fieldId: string,
requestedTypes: JsonType[]
): Promise<CQRSCommand[]> => {
const spectacleClient = new SpectacleClient(spectacle);
try {
return spectacleClient.fetchFieldEditCommands(fieldId, requestedTypes);
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
};
const fetchFieldRemoveCommands = async (
spectacle: IForkableSpectacle,
fieldId: string
): Promise<CQRSCommand[]> => {
const spectacleClient = new SpectacleClient(spectacle);
try {
return spectacleClient.fetchFieldRemoveCommands(fieldId);
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
};
export const saveDocumentationChanges = createAsyncThunk<
{},
{
spectacle: IForkableSpectacle;
commitMessage: string;
},
{
dispatch: AppDispatch;
state: RootState;
}
>(
'SAVE_DOCUMENTATION_CHANGES',
async ({ spectacle, commitMessage }, thunkApi) => {
const state = thunkApi.getState();
const clientId = state.metadata.data?.clientAgent || '';
const clientSessionId = state.metadata.data?.sessionId || '';
const { removedEndpoints } = state.documentationEdits;
const {
removed: removedFields,
edited: editedFields,
} = state.documentationEdits.fields;
const editFieldCommandsPromise: Promise<CQRSCommand[]> = Promise.all(
Object.entries(editedFields).map(([fieldId, options]) => {
const requestedTypes: JsonType[] = [];
if (options.isNullable) {
requestedTypes.push(JsonType.NULL);
}
if (options.isOptional) {
requestedTypes.push(JsonType.UNDEFINED);
}
return fetchFieldEditCommands(spectacle, fieldId, requestedTypes);
})
).then((fieldCommands) => fieldCommands.flat());
const removeFieldCommandsPromise: Promise<CQRSCommand[]> = Promise.all(
removedFields.map((fieldId) =>
fetchFieldRemoveCommands(spectacle, fieldId)
)
).then((fieldCommands) => fieldCommands.flat());
const removeEndpointCommandsPromise: Promise<CQRSCommand[]> = Promise.all(
removedEndpoints.map(({ pathId, method }) =>
fetchRemoveEndpointCommands(
spectacle,
pathId,
method
).then((removeCommands) =>
removeCommands.concat([PrunePathComponents()])
)
)
).then((endpointCommands) => endpointCommands.flat());
const [
editFieldCommands,
removeFieldCommands,
removeEndpointCommands,
] = await Promise.all([
editFieldCommandsPromise,
removeFieldCommandsPromise,
removeEndpointCommandsPromise,
]);
const validContributions = getValidContributions(state);
const contributionCommands: CQRSCommand[] = validContributions.map(
(contribution) =>
AddContribution(
contribution.id,
contribution.contributionKey,
contribution.value
)
);
// Apply these in order for consistency - we generate the commands in parallel and then apply them all at once
// To be safer, we could apply the commands sequentially before generating the next commands
const commands = [
...contributionCommands,
...editFieldCommands,
...removeFieldCommands,
...removeEndpointCommands,
];
if (commands.length > 0) {
try {
await spectacle.mutate({
query: `
mutation X(
$commands: [JSON!]!,
$batchCommitId: ID!,
$commitMessage: String!,
$clientId: ID!,
$clientSessionId: ID!
) {
applyCommands(
commands: $commands,
batchCommitId: $batchCommitId,
commitMessage: $commitMessage,
clientId: $clientId,
clientSessionId: $clientSessionId
) {
batchCommitId
}
}
`,
variables: {
commands,
commitMessage,
batchCommitId: uuidv4(),
clientId,
clientSessionId,
},
});
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
}
}
);
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelogHistory/components/ConfirmResetModal.tsx
|
import React, { FC, useState } from 'react';
import {
Dialog,
DialogActions,
DialogContent,
DialogTitle,
makeStyles,
} from '@material-ui/core';
import * as Sentry from '@sentry/react';
import { Button } from '<src>/components';
import { useSpectacleContext } from '<src>/contexts/spectacle-provider';
import { BatchCommit } from '<src>/hooks/useBatchCommits';
import { formatTimeAgo } from '<src>/utils';
type ConfirmResetModalProps = {
onClose: () => void;
onSave?: () => void;
batchCommit: BatchCommit;
};
export const ConfirmResetModal: FC<ConfirmResetModalProps> = ({
onClose,
onSave: onSaveProp,
batchCommit,
}) => {
const spectacle = useSpectacleContext();
const [isSaving, setIsSaving] = useState(false);
const classes = useStyles();
const onSave = async (batchCommitId: string) => {
onSaveProp && onSaveProp();
try {
const results = await spectacle.mutate<{}, { batchCommitId: string }>({
query: `
mutation X(
$batchCommitId: ID!
) {
resetToCommit(batchCommitId: $batchCommitId)
}
`,
variables: {
batchCommitId,
},
});
if (results.errors) {
console.error(results.errors);
throw new Error(JSON.stringify(results.errors));
}
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
};
return (
<Dialog open={true} onClose={onClose}>
<DialogTitle>Reset to commit {batchCommit.batchId}</DialogTitle>
<DialogContent>
<h4 className={classes.commitDetailsHeader}>Details</h4>
<div className={classes.commitDetails}>
<p className={classes.commitMessage}>{batchCommit.commitMessage}</p>
<p className={classes.commitTimeAgo}>
{formatTimeAgo(new Date(batchCommit.createdAt))}
</p>
</div>
</DialogContent>
<DialogContent>
This will hard reset your specification to this commit (there will be no
history for this reset). Are you sure you want to continue?
</DialogContent>
<DialogActions>
<Button onClick={onClose} color="default">
Cancel
</Button>
<Button
disabled={isSaving}
onClick={async () => {
setIsSaving(true);
await onSave(batchCommit.batchId);
onClose();
}}
color="primary"
loading={isSaving}
>
Confirm
</Button>
</DialogActions>
</Dialog>
);
};
const useStyles = makeStyles((theme) => ({
commitDetailsHeader: {
marginTop: 0,
},
commitDetails: {
borderLeft: `2px solid ${theme.palette.grey[300]}`,
paddingLeft: theme.spacing(2),
},
commitMessage: {
margin: 0,
},
commitTimeAgo: {
margin: 0,
},
}));
|
tony-aq/optic
|
workspaces/cli-server/src/standalone-server.ts
|
import { CliServer } from './server';
import { Client } from '@useoptic/cli-client';
async function main(inputs: { opticProjectDirectory: string }) {
const apiServer = new CliServer({
cloudApiBaseUrl: 'fixme',
});
const serverState = await apiServer.start();
const baseUrl = `http://localhost:${serverState.port}/api`;
console.log(`server started on ${baseUrl}`);
const cliClient = new Client(baseUrl);
const x = await cliClient.findSession(
inputs.opticProjectDirectory,
null,
null
);
console.log(`navigate to http://localhost:3000/apis/${x.session.id}`);
}
const [, , opticProjectDirectory] = process.argv;
main({ opticProjectDirectory });
|
tony-aq/optic
|
workspaces/ui-v2/src/components/Panel.tsx
|
import React, { FC, Ref } from 'react';
import classNames from 'classnames';
import { makeStyles } from '@material-ui/core';
import { FontFamilyMono } from '<src>/styles';
type PanelProps = {
header: React.ReactNode;
contentRef?: Ref<HTMLDivElement>;
};
export const Panel: FC<
PanelProps & React.HtmlHTMLAttributes<HTMLDivElement>
> = ({ children, header, className, contentRef, ...props }) => {
const classes = useStyles();
return (
<div {...props} className={classNames(classes.wrapper, className)}>
<div className={classes.header}>
<div>{header}</div>
</div>
<div className={classes.content} ref={contentRef}>
{children}
</div>
</div>
);
};
const useStyles = makeStyles((theme) => ({
wrapper: {
overflow: 'hidden',
width: '100%',
},
header: {
display: 'flex',
backgroundColor: '#e4e8ed',
color: '#4f566b',
fontSize: theme.typography.fontSize - 1,
height: theme.spacing(4),
paddingLeft: theme.spacing(2),
fontFamily: FontFamilyMono,
alignItems: 'center',
overflow: 'hidden',
borderTopLeftRadius: theme.shape.borderRadius * 2,
borderTopRightRadius: theme.shape.borderRadius * 2,
borderBottom: '1px solid #e2e2e2',
},
content: {
backgroundColor: '#f8fafc',
padding: theme.spacing(1),
maxHeight: '80vh',
overflowY: 'auto',
borderLeft: '1px solid #e4e8ed',
borderRight: '1px solid #e4e8ed',
borderBottom: '1px solid #e4e8ed',
borderBottomRightRadius: theme.shape.borderRadius,
borderBottomLeftRadius: theme.shape.borderRadius,
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/store/index.ts
|
export * from './root';
export { actions as diffActions } from './diff';
export { actions as pathsActions } from './paths';
export { actions as endpointActions } from './endpoints';
export { actions as documentationEditActions } from './documentationEdit';
export { actions as shapeActions } from './shapes';
export { actions as metadataActions } from './metadata';
export * as selectors from './selectors';
|
tony-aq/optic
|
workspaces/ui-v2/src/components/DataFetchers.tsx
|
<filename>workspaces/ui-v2/src/components/DataFetchers.tsx
import React, { FC, useEffect } from 'react';
import {
shapeActions,
selectors,
useAppSelector,
useAppDispatch,
} from '<src>/store';
import { useSpectacleContext } from '<src>/contexts/spectacle-provider';
import { IFieldDetails, IShapeRenderer } from '<src>/types';
import { Loader } from './loaders';
type ShapeFetcherProps = {
rootShapeId: string;
changesSinceBatchCommit?: string;
endpointId: string;
children: (
shapes: IShapeRenderer[],
fieldList: IFieldDetails[]
) => React.ReactElement;
};
export const ShapeFetcher: FC<ShapeFetcherProps> = ({
rootShapeId,
changesSinceBatchCommit,
endpointId,
children,
}) => {
const spectacle = useSpectacleContext();
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(
shapeActions.fetchShapes({
spectacle,
rootShapeId,
sinceBatchCommitId: changesSinceBatchCommit,
})
);
}, [dispatch, spectacle, rootShapeId, changesSinceBatchCommit]);
const shapesState = useAppSelector(selectors.getShapeRenderer(rootShapeId));
return shapesState.loading ? (
<Loader title="Loading" />
) : shapesState.error ? (
<div>error</div>
) : (
children(
shapesState.data,
selectors.createFlatList(shapesState.data, endpointId)
)
);
};
|
tony-aq/optic
|
workspaces/cli-shared/src/conversation.ts
|
import colors from 'colors';
import { promise as OraPromise, Options as OraOptions } from 'ora';
export function fromOptic(msg: string) {
return msg
.split('\n')
.map((line) => `${colors.cyan('[optic]')} ${line}`)
.join('\n');
}
export function fromOpticVerbose(msg: string) {
return msg
.split('\n')
.map((line) => `${colors.blue('[optic-verbose]')} ${line}`)
.join('\n');
}
export function errorFromOptic(msg: string) {
return msg
.split('\n')
.map((line) => `${colors.cyan('[optic]')} ${colors.red(line)}`)
.join('\n');
}
export function warningFromOptic(msg: string) {
return msg
.split('\n')
.map((line) => `${colors.cyan('[optic]')} ${colors.yellow(line)}`)
.join('\n');
}
export function promiseFromOptic(
promise: PromiseLike<unknown>,
msgOrOptions: string | OraOptions
) {
let options =
typeof msgOrOptions === 'string'
? {
text: msgOrOptions,
}
: msgOrOptions;
return OraPromise(promise, {
...options,
prefixText: colors.cyan('[optic]'),
});
}
export { colors };
|
tony-aq/optic
|
workspaces/shape-hash/src/index.ts
|
import { jsonToShapeHash, toBytes, toJsonExample } from './json-to-shape-hash';
export { jsonToShapeHash, toBytes, toJsonExample };
|
tony-aq/optic
|
workspaces/optic-domain/tests/engine.ts
|
import Tap from 'tap';
import * as OpticEngine from '@useoptic/optic-engine-wasm/build';
Tap.test('OpticEngine spec_from_events', async (test) => {
let spec = OpticEngine.spec_from_events('[]');
test.ok(spec);
});
|
tony-aq/optic
|
workspaces/ui-v2/src/types/index.ts
|
<reponame>tony-aq/optic
export * from './async';
export * from './changes';
export * from './contributions';
export * from './endpoints';
export * from './shapes';
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ContributionsList/ContributionList.tsx
|
<gh_stars>100-1000
import React, { FC } from 'react';
import { IFieldDetails } from '<src>/types';
type ContributionsListProps = {
fieldDetails: IFieldDetails[];
renderField: (contribution: IFieldDetails) => React.ReactElement;
};
export const ContributionsList: FC<ContributionsListProps> = ({
fieldDetails,
renderField,
}) => {
return <>{fieldDetails.map(renderField)}</>;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/store/endpoints/thunks.ts
|
import { createAsyncThunk } from '@reduxjs/toolkit';
import * as Sentry from '@sentry/react';
import { IForkableSpectacle } from '@useoptic/spectacle';
import { ChangeType, IEndpoint } from '<src>/types';
import { getEndpointId } from '<src>/utils';
import groupBy from 'lodash.groupby';
import {
convertSpectacleChangeToChangeType,
SpectacleChange,
} from '../spectacleUtils';
export const AllEndpointsQuery = `
query X($sinceBatchCommitId: String) {
endpoints {
id
pathId
method
pathComponents {
id
name
isParameterized
contributions
isRemoved
}
pathPattern
query {
id
rootShapeId
isRemoved
contributions
changes(sinceBatchCommitId: $sinceBatchCommitId) {
added
changed
removed
}
}
requests {
id
body {
contentType
rootShapeId
}
changes(sinceBatchCommitId: $sinceBatchCommitId) {
added
changed
removed
}
contributions
isRemoved
}
responses {
id
statusCode
contributions
bodies {
contentType
rootShapeId
}
changes(sinceBatchCommitId: $sinceBatchCommitId) {
added
changed
removed
}
isRemoved
}
isRemoved
contributions
}
}`;
export const EndpointChangeQuery = `query X($sinceBatchCommitId: String) {
endpointChanges(sinceBatchCommitId: $sinceBatchCommitId) {
endpoints {
change {
category
}
pathId
method
}
}
}`;
type EndpointChangelog = {
change: {
category: ChangeType;
};
pathId: string;
method: string;
};
type EndpointChangeQueryResults = {
endpointChanges: {
endpoints: EndpointChangelog[];
};
};
type HttpBody = {
contentType: string;
rootShapeId: string;
};
export type EndpointQueryResults = {
endpoints: {
id: string;
pathId: string;
method: string;
pathPattern: string;
pathComponents: {
id: string;
name: string;
isParameterized: boolean;
contributions: Record<string, string>;
isRemoved: boolean;
}[];
query?: {
id: string;
rootShapeId?: string;
isRemoved: boolean;
changes: SpectacleChange;
contributions: Record<string, string>;
};
requests: {
id: string;
body?: HttpBody;
contributions: Record<string, string>;
changes: SpectacleChange;
isRemoved: boolean;
}[];
responses: {
id: string;
statusCode: number;
contributions: Record<string, string>;
changes: SpectacleChange;
bodies: HttpBody[];
isRemoved: boolean;
}[];
isRemoved: boolean;
contributions: Record<string, string>;
}[];
};
export const endpointQueryResultsToJson = (
{ endpoints }: EndpointQueryResults,
endpointChanges: EndpointChangeQueryResults | null,
includeChanges: boolean
): {
endpoints: IEndpoint[];
changes: Record<string, ChangeType>;
} => {
const changes: Record<string, ChangeType> = {};
const mappedEndpoints = endpoints.map((endpoint) => {
if (endpoint.query) {
const change = convertSpectacleChangeToChangeType(endpoint.query.changes);
if (change) {
changes[endpoint.query.id] = change;
}
}
return {
id: endpoint.id,
pathId: endpoint.pathId,
method: endpoint.method,
description: endpoint.contributions.description || '',
purpose: endpoint.contributions.purpose || '',
isRemoved: endpoint.isRemoved,
fullPath: endpoint.pathPattern,
pathParameters: endpoint.pathComponents.map((path) => ({
id: path.id,
name: path.name,
isParameterized: path.isParameterized,
description: path.contributions.description || '',
endpointId: endpoint.id,
})),
query:
endpoint.query && endpoint.query.rootShapeId
? {
queryParametersId: endpoint.query.id,
rootShapeId: endpoint.query.rootShapeId,
isRemoved: endpoint.query.isRemoved,
description: endpoint.query.contributions.description || '',
endpointId: endpoint.id,
pathId: endpoint.pathId,
method: endpoint.method,
}
: null,
requests: endpoint.requests.map((request) => {
const change = convertSpectacleChangeToChangeType(request.changes);
if (change) {
changes[request.id] = change;
}
return {
requestId: request.id,
body: request.body
? {
rootShapeId: request.body.rootShapeId,
contentType: request.body.contentType,
}
: null,
description: request.contributions.description || '',
endpointId: endpoint.id,
pathId: endpoint.pathId,
method: endpoint.method,
isRemoved: request.isRemoved,
};
}),
// Group by status code
responsesByStatusCode: groupBy(
endpoint.responses.map((response) => {
const change = convertSpectacleChangeToChangeType(response.changes);
if (change) {
changes[response.id] = change;
}
return {
responseId: response.id,
statusCode: response.statusCode,
description: response.contributions.description || '',
endpointId: endpoint.id,
pathId: endpoint.pathId,
method: endpoint.method,
isRemoved: response.isRemoved,
body:
response.bodies.length >= 1
? {
rootShapeId: response.bodies[0].rootShapeId,
contentType: response.bodies[0].contentType,
}
: null,
};
}),
'statusCode'
),
};
});
if (endpointChanges) {
endpointChanges.endpointChanges.endpoints.forEach(
({ pathId, method, change }) => {
const endpointId = getEndpointId({ pathId, method });
changes[endpointId] = change.category;
}
);
}
return { endpoints: mappedEndpoints, changes: includeChanges ? changes : {} };
};
export const fetchEndpoints = createAsyncThunk<
ReturnType<typeof endpointQueryResultsToJson>,
{ spectacle: IForkableSpectacle; sinceBatchCommitId?: string }
>('FETCH_ENDPOINTS', async ({ spectacle, sinceBatchCommitId }) => {
try {
const resultsPromise = spectacle.query<
EndpointQueryResults,
{
sinceBatchCommitId?: string;
}
>({
query: AllEndpointsQuery,
variables: {
sinceBatchCommitId,
},
});
const endpointChangesPromise = sinceBatchCommitId
? spectacle.query<
EndpointChangeQueryResults,
{
sinceBatchCommitId?: string;
}
>({
query: EndpointChangeQuery,
variables: { sinceBatchCommitId },
})
: Promise.resolve(null);
const [results, endpointChanges] = await Promise.all([
resultsPromise,
endpointChangesPromise,
]);
if (results.errors) {
console.error(results.errors);
throw new Error(JSON.stringify(results.errors));
}
if (endpointChanges && endpointChanges.errors) {
console.error(endpointChanges.errors);
throw new Error(JSON.stringify(endpointChanges.errors));
}
return endpointQueryResultsToJson(
results.data!,
endpointChanges?.data || null,
sinceBatchCommitId !== undefined
);
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
});
|
tony-aq/optic
|
workspaces/spectacle/src/index.ts
|
<gh_stars>100-1000
export * from './openapi';
export * from './spectacle';
export * from './types';
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/onboarding/WelcomePage.tsx
|
import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
body: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100vh',
},
}));
export default function WelcomePage() {
const classes = useStyles();
return <div className={classes.body}>welcome</div>;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/AddEndpointsPage/hooks/index.ts
|
export * from './useCheckboxState';
|
tony-aq/optic
|
workspaces/cli-server/src/routers/spec-router.ts
|
import {
getPathsRelativeToCwd,
IOpticTaskRunnerConfig,
parseRule,
readApiConfig,
} from '@useoptic/cli-config';
import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';
import fs from 'fs-extra';
import Bottleneck from 'bottleneck';
import sortBy from 'lodash.sortby';
import { DefaultIdGenerator, developerDebugLogger } from '@useoptic/cli-shared';
import { makeRouter as makeCaptureRouter } from './capture-router';
import { LocalCaptureInteractionPointerConverter } from '@useoptic/cli-shared/build/captures/avro/file-system/interaction-iterator';
import { IgnoreFileHelper } from '@useoptic/cli-config/build/helpers/ignore-file-interface';
import { SessionsManager } from '../sessions';
import { patchInitialTaskOpticYaml } from '@useoptic/cli-config/build/helpers/patch-optic-config';
import { getSpecEventsFrom } from '@useoptic/cli-config/build/helpers/read-specification-json';
import { makeSpectacle } from '@useoptic/spectacle';
import { graphqlHTTP } from 'express-graphql';
import { LocalCliOpticContextBuilder } from '../spectacle';
type CaptureId = string;
type Iso8601Timestamp = string;
export type InvalidCaptureState = {
captureId: CaptureId;
status: 'unknown';
};
export function isValidCaptureState(x: CaptureState): x is ValidCaptureState {
return x.status === 'started' || x.status === 'completed';
}
export type ValidCaptureState = {
captureId: CaptureId;
status: 'started' | 'completed';
metadata: {
taskConfig: IOpticTaskRunnerConfig;
startedAt: Iso8601Timestamp;
lastInteraction: {
count: number;
observedAt: Iso8601Timestamp;
} | null;
};
};
export type CaptureState = InvalidCaptureState | ValidCaptureState;
const captureStateFileName = 'optic-capture-state.json';
export class CapturesHelpers {
constructor(private basePath: string) {}
async validateCaptureId(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const { captureId } = req.params;
const captureDirectoryPath = this.captureDirectory(captureId);
const exists = await fs.pathExists(captureDirectoryPath);
if (exists) {
return next();
} else {
return res.sendStatus(404);
}
}
async listCaptureIds(): Promise<CaptureId[]> {
const captureIds = await fs.readdir(this.basePath);
return captureIds;
}
async loadCaptureState(captureId: CaptureId): Promise<CaptureState> {
const stateFilePath = this.stateFile(captureId);
const stateFileExists = await fs.pathExists(stateFilePath);
if (!stateFileExists) {
return {
captureId,
status: 'unknown',
};
}
const state = await fs.readJson(stateFilePath);
return state;
}
async updateCaptureState(state: CaptureState): Promise<void> {
await fs.ensureDir(this.captureDirectory(state.captureId));
const stateFilePath = this.stateFile(state.captureId);
await fs.writeJson(stateFilePath, state);
}
async listCapturesState(): Promise<CaptureState[]> {
const captureIds = await this.listCaptureIds();
const promises = captureIds.map((captureId) => {
return this.loadCaptureState(captureId);
});
const capturesState = await Promise.all(promises);
return capturesState.filter((x) => x !== null);
}
async loadCaptureSummary(captureId: CaptureId) {
const captureDirectory = this.captureDirectory(captureId);
const files = await fs.readdir(captureDirectory);
const interactions = files.filter((x) => x.startsWith('interactions-'));
const promises = interactions.map((x) => {
return fs.readJson(path.join(captureDirectory, x));
});
const summaries = await Promise.all(promises);
const summary = summaries.reduce(
(acc, value) => {
acc.diffsCount = acc.diffsCount + value.diffsCount;
acc.interactionsCount = acc.interactionsCount + value.interactionsCount;
return acc;
},
{ diffsCount: 0, interactionsCount: 0 }
);
return summary;
}
stateFile(captureId: CaptureId): string {
return path.join(this.captureDirectory(captureId), captureStateFileName);
}
baseDirectory(): string {
return this.basePath;
}
captureDirectory(captureId: CaptureId): string {
return path.join(this.basePath, captureId);
}
}
export class ExampleRequestsHelpers {
constructor(private basePath: string) {}
exampleFile(requestId: string) {
return path.join(this.basePath, requestId, 'examples.json');
}
async getExampleRequests(requestId: string): Promise<any> {
const exampleFilePath = this.exampleFile(requestId);
const currentFileContents = await (async () => {
const exists = await fs.pathExists(exampleFilePath);
if (exists) {
try {
const contents = await fs.readJson(exampleFilePath);
return contents;
} catch (e) {
return [];
}
}
return [];
})();
return currentFileContents;
}
async saveExampleRequest(requestId: string, example: any) {
const exampleFilePath = this.exampleFile(requestId);
const currentFileContents = await this.getExampleRequests(requestId);
currentFileContents.push(example);
await fs.ensureFile(exampleFilePath);
await fs.writeJson(exampleFilePath, currentFileContents, { spaces: 2 });
}
}
export async function makeRouter(
sessions: SessionsManager,
fileReadBottleneck: Bottleneck
) {
async function ensureValidSpecId(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
const { specId } = req.params;
developerDebugLogger({ specId, sessions });
const session = sessions.findById(specId);
if (!session) {
res.sendStatus(404);
return;
}
try {
const paths = await getPathsRelativeToCwd(session.path);
const {
configPath,
opticIgnorePath,
capturesPath,
exampleRequestsPath,
} = paths;
const config = await readApiConfig(configPath);
const ignoreHelper = new IgnoreFileHelper(opticIgnorePath, configPath);
const capturesHelpers = new CapturesHelpers(capturesPath);
const exampleRequestsHelpers = new ExampleRequestsHelpers(
exampleRequestsPath
);
async function specLoader(): Promise<any[]> {
const events = await getSpecEventsFrom(paths.specStorePath);
return events;
}
req.optic = {
config,
paths,
ignoreHelper,
capturesHelpers,
exampleRequestsHelpers,
session,
specLoader,
};
next();
} catch (e) {
res.status(500).json({
message: e.message,
});
}
}
const router = express.Router({ mergeParams: true });
router.use(ensureValidSpecId);
// events router
router.get('/events', async (req, res) => {
try {
const events = await req.optic.specLoader();
res.json(events);
} catch (e) {
res.json([]);
}
});
const instances: Map<string, any> = new Map();
router.use(bodyParser.json({ limit: '10mb' }));
router.use('/spectacle', async (req, res) => {
let handler = instances.get(req.optic.session.id);
if (!handler) {
console.count('LocalCliOpticContextBuilder.fromDirectory');
const opticContext = await LocalCliOpticContextBuilder.fromDirectory(
req.optic.paths,
req.optic.capturesHelpers
);
const spectacle = await makeSpectacle(opticContext);
const instance = graphqlHTTP({
//@ts-ignore
schema: spectacle.executableSchema,
graphiql: true,
context: {
spectacleContext: spectacle.graphqlContext,
},
});
//@GOTCHA see if someone sneaky updated it while we weren't looking
handler = instances.get(req.optic.session.id);
if (!handler) {
instances.set(req.optic.session.id, instance);
handler = instance;
}
}
handler(req, res);
});
// captures router. cli picks captureId and writes to whatever persistence method and provides capture id to ui. api spec just shows spec?
router.get('/captures', async (req, res) => {
const captures = await req.optic.capturesHelpers.listCapturesState();
const validCaptures: ValidCaptureState[] = captures.filter((x) =>
isValidCaptureState(x)
) as ValidCaptureState[];
res.json({
captures: sortBy(validCaptures, (i) => i.metadata.startedAt)
.reverse()
.map((i) => ({
captureId: i.captureId,
startedAt: i.metadata.startedAt,
status: i.status,
lastUpdate: i.metadata.lastInteraction
? i.metadata.lastInteraction.observedAt
: i.metadata.startedAt,
links: [
{
rel: 'status',
href: `${req.baseUrl}/captures/${i.captureId}/status`,
},
],
})),
});
});
router.get('/config', async (req, res) => {
const rules = await req.optic.ignoreHelper.getCurrentIgnoreRules();
const configRaw = (
await fs.readFile(req.optic.paths.configPath)
).toString();
res.json({
config: { ...req.optic.config, ignoreRequests: rules.allRules },
configRaw,
});
});
router.post(
'/config/initial-task',
bodyParser.json({ limit: '100kb' }),
async (req, res) => {
const { task } = req.body;
const { name, definition } = task;
const newContents = patchInitialTaskOpticYaml(
req.optic.config,
definition,
name
);
await fs.writeFile(req.optic.paths.configPath, newContents);
res.sendStatus(200);
}
);
router.post(
'/config/raw',
bodyParser.json({ limit: '100kb' }),
async (req, res) => {
const { raw } = req.body;
await fs.writeFile(req.optic.paths.configPath, raw);
res.json({});
}
);
router.get('/ignores', async (req, res) => {
const rules = await req.optic.ignoreHelper.getCurrentIgnoreRules();
res.json({
rules,
});
});
router.patch(
'/ignores',
bodyParser.json({ limit: '100kb' }),
async (req, res) => {
const { rule } = req.body;
if (typeof rule === 'string' && Boolean(parseRule(rule))) {
await req.optic.ignoreHelper.appendRule(rule);
res.json({});
} else {
res.status(400).json({ message: 'Invalid ignore rule' });
}
}
);
const captureRouter = makeCaptureRouter({
idGenerator: new DefaultIdGenerator(),
interactionPointerConverterFactory: (config: {
captureId: CaptureId;
captureBaseDirectory: string;
}) => new LocalCaptureInteractionPointerConverter(config),
fileReadBottleneck: fileReadBottleneck,
});
router.use('/captures/:captureId', captureRouter);
return router;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/contexts/analytics/index.ts
|
export * from './AnalyticsStore';
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/components/DocPageNavigation.tsx
|
<reponame>tony-aq/optic
import React, { FC } from 'react';
import { PromptNavigateAway } from '<src>/components';
import { ChangesSinceDropdown } from '<src>/pages/changelog/components/ChangelogDropdown';
import { useAppConfig } from '<src>/contexts/config/AppConfiguration';
import { useAppSelector, selectors } from '<src>/store';
import { EditContributionsButton } from './EditContributionsButton';
import { ShareButton } from '<src>/components/sharing/ShareButton';
export const DocsPageAccessoryNavigation: FC = () => {
const appConfig = useAppConfig();
const isEditing = useAppSelector(
(state) => state.documentationEdits.isEditing
);
const pendingCount = useAppSelector(
selectors.getDocumentationEditStagedCount
);
return (
<div style={{ paddingRight: 10, display: 'flex', flexDirection: 'row' }}>
{appConfig.sharing.enabled && <ShareButton />}
<PromptNavigateAway shouldPrompt={isEditing && pendingCount > 0} />
<ChangesSinceDropdown />
{appConfig.allowEditing && <EditContributionsButton />}
</div>
);
};
|
tony-aq/optic
|
workspaces/api-checks/test/functional.ts
|
<reponame>tony-aq/optic
import * as fs from 'fs';
import Tap from 'tap';
import { EndpointChangeChecks, Spectacle, checks, reports } from '../src/';
Tap.test('Successful check', async (test) => {
const endpointChanges = await initEndpointChanges();
// The ./specification.json has a 404 in the only GET endpoint
// This makes this test pass
endpointChanges.on('added', checks.requireNotFoundWithGet);
const results = await endpointChanges.run();
test.matchSnapshot(reports.basicReport(results));
});
Tap.test('Failing check', async (test) => {
const endpointChanges = await initEndpointChanges();
endpointChanges.on('added', async () => 'Failing check');
const results = await endpointChanges.run();
test.matchSnapshot(reports.basicReport(results));
});
async function initEndpointChanges() {
const events = JSON.parse(
fs.readFileSync('./test/specification.json').toString()
);
const spectacle = await Spectacle.fromEvents(events);
return new EndpointChangeChecks({
// This is from the first batch commit in the ./specification.json file
sinceBatchCommitId: 'a2210088-b48c-44aa-853d-fece5e924482',
spectacle,
});
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/spectacleUtils.ts
|
<gh_stars>100-1000
import { ChangeType } from '<src>/types';
export type SpectacleChange = {
added?: boolean;
changed?: boolean;
removed?: boolean;
};
export const convertSpectacleChangeToChangeType = (
spectacleChange: SpectacleChange
): ChangeType | null =>
spectacleChange.added
? 'added'
: spectacleChange.changed
? 'updated'
: spectacleChange.removed
? 'removed'
: null;
|
tony-aq/optic
|
workspaces/cli-server/src/index.ts
|
import { Client } from '@useoptic/cli-client';
import lockfile from 'proper-lockfile';
import { CliDaemon } from './daemon';
import { fork } from 'child_process';
import fs from 'fs-extra';
import path from 'path';
import findProcess from 'find-process';
import * as uuid from 'uuid';
import {
delay,
developerDebugLogger,
ICliDaemonState,
} from '@useoptic/cli-shared';
import processExists from 'process-exists';
// @ts-ignore
import isPortReachable from 'is-port-reachable';
//@REFACTOR with xstate
async function waitForFile(
path: string,
options: { intervalMilliseconds: number; timeoutMilliseconds: number }
): Promise<void> {
let fileWatcherIsDone = false;
const timeout = delay(options.timeoutMilliseconds).then(() => {
if (fileWatcherIsDone) {
return;
}
developerDebugLogger('timed out waiting for file');
return Promise.reject(new Error('timed out waiting for file'));
});
const fileWatcher = new Promise<void>((resolve, reject) => {
const intervalId = setInterval(() => {
const exists = fs.existsSync(path);
if (exists) {
developerDebugLogger('saw file!');
clearInterval(intervalId);
fileWatcherIsDone = true;
resolve();
} else {
developerDebugLogger('did not see file, polling');
}
}, options.intervalMilliseconds);
timeout.finally(() => {
if (fileWatcherIsDone) {
return;
}
clearInterval(intervalId);
});
});
return Promise.race([timeout, fileWatcher]);
}
export async function ensureDaemonStarted(
lockFilePath: string,
cloudApiBaseUrl: string
): Promise<ICliDaemonState> {
const fileExisted = await fs.pathExists(lockFilePath);
if (!fileExisted) {
await fs.ensureFile(lockFilePath);
await fs.writeJson(lockFilePath, {});
}
await fs.ensureDir(path.dirname(lockFilePath));
const isLocked = await lockfile.check(lockFilePath);
developerDebugLogger({ isLocked });
let shouldStartDaemon = true;
if (isLocked) {
if (!fileExisted) {
developerDebugLogger('lockfile was missing but locked');
throw new Error(
`did not expect lockfile to be locked when lockfile did not exist`
);
}
//@GOTCHA: check to make sure the lockfile is accurate.
// The lockfile can be inaccurate when the daemon does not cleanly exit; for example, an abrupt system shutdown or force killing the daemon
const { port, pid } = await fs.readJson(lockFilePath);
try {
developerDebugLogger(`checking port ${port} and pid ${pid}`);
const [foundMatchingProcess, foundReachablePort] = await Promise.all([
processExists(pid),
isPortReachable(port),
]);
if (foundMatchingProcess && foundReachablePort) {
developerDebugLogger('the lockfile seems accurate');
shouldStartDaemon = false;
} else {
developerDebugLogger('the lockfile is not accurate');
shouldStartDaemon = true;
}
} catch (e) {
developerDebugLogger('the lockfile is not accurate');
developerDebugLogger(e.message);
shouldStartDaemon = true;
}
}
if (shouldStartDaemon) {
const isDebuggingEnabled =
process.env.OPTIC_DAEMON_ENABLE_DEBUGGING === 'yes';
if (isDebuggingEnabled) {
developerDebugLogger(
`node --inspect debugging enabled. go to chrome://inspect and open the node debugger`
);
}
const sentinelFileName = `optic-daemon-sentinel_${uuid.v4()}`;
const sentinelFilePath = path.join(
path.dirname(lockFilePath),
sentinelFileName
);
// fork process
const child = fork(
path.join(__dirname, 'main'),
[lockFilePath, sentinelFilePath, cloudApiBaseUrl],
{
execArgv: isDebuggingEnabled ? ['--inspect'] : [],
detached: true,
stdio: 'ignore',
}
);
child.unref();
child.on('error', (e) => {
developerDebugLogger(e);
throw e;
});
child.on('exit', (code, signal) => {
developerDebugLogger(
`daemon exited with code ${code} and signal ${signal}`
);
throw new Error(`daemon exited prematurely`);
});
await new Promise<void>(async (resolve, reject) => {
developerDebugLogger(
`waiting for lock from pid=${child.pid} sentinel file ${sentinelFilePath}`
);
try {
await waitForFile(sentinelFilePath, {
intervalMilliseconds: 50,
timeoutMilliseconds: 10000,
});
await fs.unlink(sentinelFilePath);
developerDebugLogger(`lock created from pid=${child.pid}`);
resolve();
} catch (e) {
reject(e);
}
});
}
developerDebugLogger(`trying to read lockfile contents`);
const contents = await fs.readJson(lockFilePath);
developerDebugLogger(`lockfile contents: ${JSON.stringify(contents)}`);
return contents;
}
export async function ensureDaemonStopped(lockFilePath: string): Promise<void> {
const fileExists = await fs.pathExists(lockFilePath);
if (!fileExists) {
developerDebugLogger('lockfile not present');
return;
}
const isLocked = await lockfile.check(lockFilePath);
if (!isLocked) {
developerDebugLogger('lockfile present but not locked');
return;
}
const contents = await fs.readJson(lockFilePath);
const { port } = contents;
const apiBaseUrl = `http://localhost:${port}/admin-api`;
const cliClient = new Client(apiBaseUrl);
try {
developerDebugLogger('sending shutdown request');
await cliClient.stopDaemon();
developerDebugLogger('sent shutdown request');
} catch (e) {
developerDebugLogger(e);
try {
await lockfile.unlock(lockFilePath);
} catch (e) {
developerDebugLogger(e);
const blockers = await findProcess('port', port);
if (blockers.length > 0) {
developerDebugLogger(blockers);
blockers.forEach((b) => {
developerDebugLogger(`killing PID ${b.pid}`);
process.kill(b.pid, 9);
});
}
}
await fs.unlink(lockFilePath);
}
}
export { CliDaemon };
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/components/DeleteEndpointConfirmationModal.tsx
|
import React, { FC } from 'react';
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
makeStyles,
} from '@material-ui/core';
import { EndpointName } from '<src>/components';
import { IEndpoint } from '<src>/types';
type DeleteEndpointConfirmationModalProps = {
endpoint: IEndpoint;
handleClose: () => void;
handleConfirm: () => void;
};
export const DeleteEndpointConfirmationModal: FC<DeleteEndpointConfirmationModalProps> = ({
endpoint,
handleClose,
handleConfirm,
}) => {
const classes = useStyles();
return (
<Dialog open={true} onClose={handleClose}>
<DialogTitle>Confirm delete endpoint</DialogTitle>
<DialogContent>
<DialogContentText component="div">
<div className={classes.confirmationTextContainer}>
Are you sure you want to delete endpoint the following endpoint?
<EndpointName
method={endpoint.method}
fullPath={endpoint.fullPath}
/>
</div>
<div className={classes.confirmationTextContainer}>
This will permanently delete this endpoint. You will lose all
contributions associated with this endpoint and will no longer see
this endpoint in your documentation page.
</div>
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="default">
Cancel
</Button>
<Button onClick={handleConfirm} color="secondary">
Confirm
</Button>
</DialogActions>
</Dialog>
);
};
const useStyles = makeStyles((theme) => ({
confirmationTextContainer: {
padding: '8px 0',
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/store/root.ts
|
import { configureStore } from '@reduxjs/toolkit';
import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { reducer as diffReducer } from './diff';
import { reducer as documentationEditReducer } from './documentationEdit';
import { reducer as endpointsReducer } from './endpoints';
import { reducer as metadataReducer } from './metadata';
import { reducer as pathsReducer } from './paths';
import { reducer as shapesReducer } from './shapes';
export const createReduxStore = () =>
configureStore({
reducer: {
endpoints: endpointsReducer,
documentationEdits: documentationEditReducer,
metadata: metadataReducer,
diff: diffReducer,
paths: pathsReducer,
shapes: shapesReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: false,
}),
});
export const store = createReduxStore();
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
tony-aq/optic
|
workspaces/ui-v2/src/store/shapes/index.ts
|
<filename>workspaces/ui-v2/src/store/shapes/index.ts<gh_stars>100-1000
export * from './slice';
export * from './thunks';
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/components/MarkdownBodyContribution.tsx
|
import * as React from 'react';
import { ChangeEvent } from 'react';
import makeStyles from '@material-ui/styles/makeStyles';
import { TextField } from '@material-ui/core';
import classNames from 'classnames';
import { OpticBlueReadable } from '<src>/styles';
import ReactMarkdown from 'react-markdown';
import {
useAppSelector,
useAppDispatch,
selectors,
documentationEditActions,
} from '<src>/store';
import { getEndpointId } from '<src>/utils';
export type MarkdownBodyContributionProps = {
id: string;
contributionKey: string;
defaultText: string;
initialValue: string;
endpoint: {
method: string;
pathId: string;
};
};
export function MarkdownBodyContribution({
id,
contributionKey,
defaultText,
initialValue,
endpoint,
}: MarkdownBodyContributionProps) {
const endpointId = getEndpointId(endpoint);
const classes = useStyles();
const isEditable = useAppSelector(selectors.isEndpointEditable(endpoint));
const contributionValue = useAppSelector(
(state) =>
state.documentationEdits.contributions[id]?.[contributionKey]?.value
);
const dispatch = useAppDispatch();
const value =
contributionValue !== undefined ? contributionValue : initialValue;
const inner = isEditable ? (
<TextField
inputProps={{ className: classNames(classes.contents, classes.editing) }}
fullWidth
variant="filled"
multiline
placeholder={defaultText}
value={value}
onChange={({ target: { value } }: ChangeEvent<HTMLInputElement>) => {
if (initialValue === value) {
dispatch(
documentationEditActions.removeContribution({
id,
contributionKey,
})
);
} else {
dispatch(
documentationEditActions.addContribution({
id,
contributionKey,
value,
endpointId,
})
);
}
}}
/>
) : (
<ReactMarkdown className={classes.contents} source={value || ''} />
);
return <div>{inner}</div>;
}
const useStyles = makeStyles((theme) => ({
contents: {
fontSize: 16,
lineHeight: 1.6,
color: '#4f566b',
paddingRight: 50,
},
editing: {
fontFamily: 'Ubuntu Mono',
fontWeight: 100,
},
defaultText: {
color: OpticBlueReadable,
cursor: 'pointer',
},
}));
|
tony-aq/optic
|
workspaces/cli-server/src/tasks/on-demand-initial-body-rust.ts
|
<gh_stars>100-1000
import {
InitialBodiesWorkerRust,
InitialBodiesWorkerConfig,
LearnedBodies,
} from '@useoptic/cli-shared/build/diffs/initial-bodies-worker-rust';
export { LearnedBodies };
export class OnDemandInitialBodyRust {
private worker: InitialBodiesWorkerRust;
constructor(config: InitialBodiesWorkerConfig) {
this.worker = new InitialBodiesWorkerRust(config);
}
async run(): Promise<LearnedBodies> {
return this.worker.run();
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/selectors/__tests__/documentationEditSelectors.test.ts
|
import { RootState } from '<src>/store/root';
import {
getValidContributions,
getDocumentationEditStagedCount,
isEndpointRemoved,
isEndpointEditable,
isFieldRemoved,
isFieldRemovedRoot,
isEndpointFieldEditable,
} from '../documentationEditSelectors';
import { getMockReduxStore } from './testHelpers';
let store: RootState;
beforeEach(() => {
store = getMockReduxStore();
});
describe('getValidContributions', () => {
test('returns all valid contributions', () => {
expect(getValidContributions(store)).toMatchSnapshot();
});
test('filters out contributions that are for deleted endpoints', () => {
store.documentationEdits.removedEndpoints.push({
pathId: 'path_UOIsxzICu5',
method: 'GET',
});
expect(getValidContributions(store)).toMatchSnapshot();
});
test('filters out contributions that are for deleted fields', () => {
store.documentationEdits.fields.removed.push('field_LRYtHDYkVO');
expect(getValidContributions(store)).toMatchSnapshot();
});
// TODO unskip when implemented
test.skip('filters out contributions with the same existing contributions value', () => {});
});
describe('getDocumentationEditStagedCount', () => {
test('contributions', () => {
expect(getDocumentationEditStagedCount(store)).toBe(2);
});
test('with deleted endpoints and fields', () => {
store.documentationEdits.removedEndpoints.push({
pathId: 'path_UOIsxzICu5',
method: 'GET',
});
store.documentationEdits.fields.removed.push('field_7u9pabP6VJ');
expect(getDocumentationEditStagedCount(store)).toBe(2);
});
});
test('isEndpointRemoved', () => {
store.documentationEdits.removedEndpoints.push({
pathId: 'path_UOIsxzICu5',
method: 'GET',
});
expect(
isEndpointRemoved({
pathId: 'path_UOIsxzICu5',
method: 'GET',
})(store)
).toBe(true);
expect(
isEndpointRemoved({
pathId: 'path_UOIsxzICu5',
method: 'POST',
})(store)
).toBe(false);
});
test('isEndpointEditable', () => {
store.documentationEdits.removedEndpoints.push({
pathId: 'path_UOIsxzICu5',
method: 'GET',
});
for (const isEditing of [true, false]) {
store.documentationEdits.isEditing = isEditing;
expect(
isEndpointEditable({
pathId: 'path_UOIsxzICu5',
method: 'GET',
})(store)
).toBe(false);
expect(
isEndpointEditable({
pathId: 'path_UOIsxzICu5',
method: 'POST',
})(store)
).toBe(isEditing);
}
});
test('isFieldRemoved', () => {
store.documentationEdits.fields.removed.push('field_p1mYG7RoTV');
// Fields and all nested fields should be removed
const removedFields = [
'field_p1mYG7RoTV',
'field_y1zK0XALx0',
'field_a1zK0XALx0',
'field_qqzK0XALx0',
];
const nonRemovedFields = ['field_cOmYY7RoTV'];
for (const fieldId of removedFields) {
expect(isFieldRemoved(fieldId)(store)).toBe(true);
}
for (const fieldId of nonRemovedFields) {
expect(isFieldRemoved(fieldId)(store)).toBe(false);
}
});
test('isFieldRemovedRoot', () => {
store.documentationEdits.fields.removed.push('field_p1mYG7RoTV');
// Fields and all nested fields should be removed
const removedRootFields = ['field_p1mYG7RoTV'];
const nonRemovedRootFields = ['field_cOmYY7RoTV', 'field_y1zK0XALx0'];
for (const fieldId of removedRootFields) {
expect(isFieldRemovedRoot(fieldId)(store)).toBe(true);
}
for (const fieldId of nonRemovedRootFields) {
expect(isFieldRemovedRoot(fieldId)(store)).toBe(false);
}
});
test('isEndpointFieldEditable', () => {
store.documentationEdits.fields.removed.push('field_p1mYG7RoTV');
store.documentationEdits.isEditing = true;
for (const endpointDeleted of [false, true]) {
if (endpointDeleted) {
store.documentationEdits.removedEndpoints.push({
pathId: 'path_UOIsxzICu5',
method: 'GET',
});
}
// endpoint starts as not deleted
const removedFields = ['field_p1mYG7RoTV', 'field_y1zK0XALx0'];
const nonRemovedFields = ['field_cOmYY7RoTV'];
for (const fieldId of removedFields) {
expect(
isEndpointFieldEditable({
fieldId,
pathId: 'path_UOIsxzICu5',
method: 'GET',
})(store)
).toBe(false);
}
for (const fieldId of nonRemovedFields) {
expect(
isEndpointFieldEditable({
fieldId,
pathId: 'path_UOIsxzICu5',
method: 'GET',
})(store)
).toBe(!endpointDeleted);
}
}
});
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/parse-diff.ts
|
import jsonStringify from 'json-stable-stringify';
//@ts-ignore
import sha1 from 'node-sha1';
import {
IJsonTrail,
normalize,
} from '@useoptic/cli-shared/build/diffs/json-trail';
import {
IDiff,
IDiffWithShapeDiff,
IShapeDiffResult,
} from '@useoptic/cli-shared/build/diffs/diffs';
import { IInteractionTrail } from '@useoptic/cli-shared/build/diffs/interaction-trail';
import { IRequestSpecTrail } from '@useoptic/cli-shared/build/diffs/request-spec-trail';
import {
IShapeTrail,
normalizeShapeTrail,
} from '@useoptic/cli-shared/build/diffs/shape-trail';
import {
allowedDiffTypes,
allowedDiffTypesKeys,
CurrentSpecContext,
isBodyShapeDiff,
} from './Interfaces';
import {
locationForTrails,
LocationDescriptor,
} from '@useoptic/cli-shared/build/diffs/trail-parsers';
import { InvariantViolationError } from '<src>/errors';
export class DiffLocation {
constructor(
public pathId: string,
public method: string,
private descriptor: LocationDescriptor
) {}
isQueryParameter(): boolean {
return (
this.descriptor.type === 'query' || this.descriptor.type === 'path_query'
);
}
isRequest(): boolean {
return (
this.descriptor.type === 'request' ||
this.descriptor.type === 'path_request'
);
}
isResponse(): boolean {
return (
this.descriptor.type === 'response' ||
this.descriptor.type === 'path_response'
);
}
getQueryParametersId(): string | null {
return this.descriptor.type === 'query'
? this.descriptor.queryParametersId
: null;
}
getRequestDescriptor(): {
requestId?: string; // requestId only lives on descriptor.type === 'request'
contentType: string;
} | null {
if (this.descriptor.type === 'request') {
return {
requestId: this.descriptor.requestId,
contentType: this.descriptor.contentType,
};
} else if (this.descriptor.type === 'path_request') {
return {
contentType: this.descriptor.contentType,
};
} else {
return null;
}
}
getResponseDescriptor(): {
responseId?: string; // responseId only lives on descriptor.type === 'responseId'
contentType?: string; // content type is nullable on path_response ????
statusCode: number;
} | null {
if (this.descriptor.type === 'response') {
return {
responseId: this.descriptor.responseId,
contentType: this.descriptor.contentType,
statusCode: this.descriptor.statusCode,
};
} else if (this.descriptor.type === 'path_response') {
return {
contentType: this.descriptor.contentType,
statusCode: this.descriptor.statusCode,
};
} else {
return null;
}
}
}
// TODO QPB rewrite ParsedDiff to have better type safety and better utility functions
export class ParsedDiff {
diffType: string;
diffHash: string;
constructor(
private serialized_diff: IDiff,
public interactions: string[],
fingerprint: string
) {
const keys = Object.keys(this.serialized_diff);
const typeKey = keys[0]!;
if (!(keys.length === 1 && allowedDiffTypesKeys.includes(typeKey))) {
throw new InvariantViolationError(
'Serialized diffs should only have one root key'
);
}
this.diffHash = fingerprint;
this.diffType = typeKey!;
}
toString() {
return '';
}
raw(): IDiff {
return this.serialized_diff;
}
interactionTrail(): IInteractionTrail {
const key = Object.keys(this.serialized_diff)[0];
// @ts-ignore
return this.serialized_diff[key].interactionTrail;
}
requestsTrail(): IRequestSpecTrail {
const key = Object.keys(this.serialized_diff)[0];
// @ts-ignore
return this.serialized_diff[key].requestsTrail;
}
affectsADocumentedEndpoint(currentSpecContext: CurrentSpecContext) {
const location = this.location(currentSpecContext);
if (!location) {
return false;
}
const allEndpoints = currentSpecContext.currentSpecEndpoints;
const isDocumented = allEndpoints.find(
(i: any) => i.pathId === location.pathId && i.method === location.method
);
return location.pathId && !!isDocumented;
}
location(currentSpecContext: CurrentSpecContext): DiffLocation {
const endpoints = currentSpecContext.currentSpecEndpoints;
const location = locationForTrails(
this.requestsTrail(),
this.interactionTrail(),
endpoints.map((endpoint) => ({
pathId: endpoint.pathId,
method: endpoint.method,
query: endpoint.query,
requests: endpoint.requests
.filter((request) => !!request.body)
.map((request) => ({
requestId: request.requestId,
contentType: request.body!.contentType,
})),
responses: Object.values(endpoint.responsesByStatusCode).flatMap(
(responses) =>
responses
.filter((response) => !!response.body)
.map((response) => ({
responseId: response.responseId,
statusCode: response.statusCode,
contentType: response.body!.contentType,
}))
),
}))
);
if (!location) {
throw new InvariantViolationError('no location found for diff');
}
return new DiffLocation(
location.pathId,
location.method,
location.descriptor
);
}
isNewRegionDiff(): boolean {
return !isBodyShapeDiff(this.diffType);
}
isBodyShapeDiff(): boolean {
return isBodyShapeDiff(this.diffType);
}
isA(k: string): boolean {
return this.diffType === k;
}
asShapeDiff(
currentSpecContext: CurrentSpecContext
): BodyShapeDiff | undefined {
if (!isBodyShapeDiff(this.diffType)) {
return undefined;
}
const asWithShapeDiff = this.serialized_diff as IDiffWithShapeDiff;
const queryParameterBodyShapeDiff: IShapeDiffResult | undefined =
// @ts-ignore
asWithShapeDiff[allowedDiffTypes.UnmatchedQueryParametersShape.asString]
?.shapeDiffResult;
const requestBodyShapeDiff: IShapeDiffResult | undefined =
// @ts-ignore
asWithShapeDiff[allowedDiffTypes.UnmatchedRequestBodyShape.asString]
?.shapeDiffResult;
const responseBodyShapeDiff: IShapeDiffResult | undefined =
// @ts-ignore
asWithShapeDiff[allowedDiffTypes.UnmatchedResponseBodyShape.asString]
?.shapeDiffResult;
return new BodyShapeDiff(
this,
this.serialized_diff,
// TODO QPB - remove the ! here
(queryParameterBodyShapeDiff ||
requestBodyShapeDiff ||
responseBodyShapeDiff)!,
this.interactions,
this.location(currentSpecContext)
);
}
}
export class BodyShapeDiff {
shapeTrail: IShapeTrail;
normalizedShapeTrail: IShapeTrail;
jsonTrail: IJsonTrail;
shapeDiffGroupingHash: string;
isUnmatched: boolean;
isUnspecified: boolean;
constructor(
private parsedDiff: ParsedDiff,
private diff: IDiff,
private shapeDiff: IShapeDiffResult,
public interactionPointers: string[],
public location: DiffLocation
) {
// @ts-ignore
this.shapeTrail = (shapeDiff['UnmatchedShape']?.shapeTrail ||
// @ts-ignore
shapeDiff['UnspecifiedShape']?.shapeTrail)!;
if (!this.shapeTrail) {
throw new InvariantViolationError(
'A shape trail must be specified with all shape diffs'
);
}
this.normalizedShapeTrail = normalizeShapeTrail(this.shapeTrail);
this.jsonTrail = normalize(
// @ts-ignore
shapeDiff['UnmatchedShape']?.jsonTrail ||
// @ts-ignore
shapeDiff['UnspecifiedShape']?.jsonTrail
)!;
this.shapeDiffGroupingHash = sha1(
jsonStringify(normalizeShapeTrail(this.shapeTrail)) +
jsonStringify(this.jsonTrail)
);
// @ts-ignore
this.isUnmatched = Boolean(shapeDiff['UnmatchedShape']);
// @ts-ignore
this.isUnspecified = Boolean(shapeDiff['UnspecifiedShape']);
}
diffHash() {
return this.parsedDiff.diffHash;
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/lib/shape-trail-parser.ts
|
import {
IListItemTrail,
IListTrail,
INullableTrail,
IObjectFieldTrail,
IObjectTrail,
IOneOfItemTrail,
IOptionalTrail,
IOptionalItemTrail,
IShapeTrail,
IShapeTrailComponent,
} from '@useoptic/cli-shared/build/diffs/shape-trail';
import { ICoreShapeKinds, JsonType } from '@useoptic/optic-domain';
import { InvariantViolationError } from '<src>/errors';
export interface IExpectationHelper {
allowedCoreShapes: string[];
allowedCoreShapeKindsByShapeId: { [key: string]: ICoreShapeKinds };
lastField?: string;
lastFieldShapeId?: string;
fieldIsOptional?: boolean;
lastObject?: string;
lastList?: string;
lastListItem?: string;
rootShapeId?: string;
shapeName?: string;
}
export async function shapeTrailParserLastId(
shapeTrail: IShapeTrail,
spectacle: any
): Promise<IExpectationHelper> {
const lastTrail: IShapeTrailComponent =
shapeTrail.path[shapeTrail.path.length - 1];
if (lastTrail) {
if (lastTrail.hasOwnProperty('ObjectTrail')) {
const shapeId = (lastTrail as IObjectTrail).ObjectTrail.shapeId;
const choices = await getChoices(shapeId, spectacle);
const lastObjectOption = Object.entries(
choices.allowedCoreShapeKindsByShapeId
).find(([key, value]) => value === ICoreShapeKinds.ObjectKind);
return {
lastObject: lastObjectOption ? lastObjectOption[0] : undefined,
...choices,
};
}
if (lastTrail.hasOwnProperty('OneOfItemTrail')) {
const shapeId = (lastTrail as IOneOfItemTrail).OneOfItemTrail.itemShapeId;
const choices = await getChoices(shapeId, spectacle);
return {
...choices,
};
}
if (lastTrail.hasOwnProperty('ObjectFieldTrail')) {
const fieldTrail = (lastTrail as IObjectFieldTrail).ObjectFieldTrail;
const choices = await getChoices(fieldTrail.fieldShapeId, spectacle);
const lastObjectOption = Object.entries(
choices.allowedCoreShapeKindsByShapeId
).find(([key, value]) => value === ICoreShapeKinds.ObjectKind);
return {
lastObject: lastObjectOption
? lastObjectOption[0]
: fieldTrail.parentObjectShapeId,
lastField: fieldTrail.fieldId,
lastFieldShapeId: fieldTrail.fieldShapeId,
fieldIsOptional: choices.allowedCoreShapes.includes(
ICoreShapeKinds.OptionalKind
),
...choices,
};
}
if (lastTrail.hasOwnProperty('ListTrail')) {
const shapeId = (lastTrail as IListTrail).ListTrail.shapeId;
const choices = await getChoices(shapeId, spectacle);
return {
lastList: shapeId,
...choices,
};
}
if (lastTrail.hasOwnProperty('ListItemTrail')) {
const listItemTrail = (lastTrail as IListItemTrail).ListItemTrail;
const choices = await getChoices(listItemTrail.itemShapeId, spectacle);
const lastObjectOption = Object.entries(
choices.allowedCoreShapeKindsByShapeId
).find(([key, value]) => value === ICoreShapeKinds.ObjectKind);
return {
lastObject: lastObjectOption ? lastObjectOption[0] : undefined,
lastList: listItemTrail.listShapeId,
lastListItem: listItemTrail.itemShapeId,
...choices,
};
}
//
if (lastTrail.hasOwnProperty('NullableTrail')) {
const shapeId = (lastTrail as INullableTrail).NullableTrail.shapeId;
const choices = await getChoices(shapeId, spectacle);
const lastItems = await shapeTrailParserLastId(
{
...shapeTrail,
path: [...shapeTrail.path.slice(0, shapeTrail.path.length - 1)],
},
spectacle
);
return {
lastObject: lastItems.lastObject,
lastField: lastItems.lastField,
lastFieldShapeId: lastItems.lastFieldShapeId,
...choices,
};
}
if (lastTrail.hasOwnProperty('OptionalTrail')) {
const shapeId = (lastTrail as IOptionalTrail).OptionalTrail.shapeId;
const choices = await getChoices(shapeId, spectacle);
const lastItems = await shapeTrailParserLastId(
{
...shapeTrail,
path: [...shapeTrail.path.slice(0, shapeTrail.path.length - 1)],
},
spectacle
);
return {
lastObject: lastItems.lastObject,
lastField: lastItems.lastField,
lastFieldShapeId: lastItems.lastFieldShapeId,
...choices,
};
}
if (lastTrail.hasOwnProperty('OptionalItemTrail')) {
const optionalItemTrail = (lastTrail as IOptionalItemTrail)
.OptionalItemTrail;
const choices = await getChoices(
optionalItemTrail.innerShapeId,
spectacle
);
const lastItems = await shapeTrailParserLastId(
{
...shapeTrail,
path: [...shapeTrail.path.slice(0, shapeTrail.path.length - 1)],
},
spectacle
);
return {
lastObject: lastItems.lastObject,
lastField: lastItems.lastField,
lastFieldShapeId: lastItems.lastFieldShapeId,
...choices,
};
}
throw new InvariantViolationError('shape trail could not be parsed');
} else {
const choices = await getChoices(shapeTrail.rootShapeId, spectacle);
const lastObject = Object.entries(
choices.allowedCoreShapeKindsByShapeId
).find(([id, kind]) => {
return kind === ICoreShapeKinds.ObjectKind;
})?.[0];
return {
...choices,
lastObject,
rootShapeId: shapeTrail.rootShapeId,
};
}
}
async function getChoices(
shapeId: string,
spectacle: any
): Promise<{
allowedCoreShapes: string[];
allowedCoreShapeKindsByShapeId: { [key: string]: ICoreShapeKinds };
}> {
const query = `
query X($shapeId: ID) {
shapeChoices(shapeId: $shapeId) {
id
jsonType
}
}`;
const result = await spectacle.query({
variables: {
shapeId: shapeId,
},
query,
});
if (result.data) {
const shapeChoices: {
id: string;
coreShapeKind: ICoreShapeKinds;
}[] = JsonLikeToCoreShapeKinds(result.data.shapeChoices, shapeId);
const allowedCoreShapeKindsByShapeId: {
[key: string]: ICoreShapeKinds;
} = {};
shapeChoices.forEach(
(i) => (allowedCoreShapeKindsByShapeId[i.id] = i.coreShapeKind)
);
return {
allowedCoreShapeKindsByShapeId,
allowedCoreShapes: shapeChoices.map((i) => i.coreShapeKind),
};
} else {
return { allowedCoreShapeKindsByShapeId: {}, allowedCoreShapes: [] };
}
}
export function JsonLikeToCoreShapeKinds(
jsonLikes: { id: string; jsonType: JsonType }[],
rootShapeId: string
): { id: string; coreShapeKind: ICoreShapeKinds }[] {
//@todo talk about how we will handle todos
if (jsonLikes.length === 0) {
return [];
}
function toCoreShapeKind(jsonLike: JsonType): ICoreShapeKinds {
switch (jsonLike) {
case JsonType.OBJECT:
return ICoreShapeKinds.ObjectKind;
case JsonType.STRING:
return ICoreShapeKinds.StringKind;
case JsonType.BOOLEAN:
return ICoreShapeKinds.BooleanKind;
case JsonType.NULL:
return ICoreShapeKinds.NullableKind;
case JsonType.NUMBER:
return ICoreShapeKinds.NumberKind;
case JsonType.UNDEFINED:
return ICoreShapeKinds.OptionalKind;
case JsonType.ARRAY:
return ICoreShapeKinds.ListKind;
}
}
return jsonLikes.map((i) => {
return {
id: i.id || rootShapeId,
coreShapeKind: toCoreShapeKind(i.jsonType),
};
});
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ContributionsList/index.ts
|
<reponame>tony-aq/optic<filename>workspaces/ui-v2/src/components/ContributionsList/index.ts
export * from './ContributionList';
|
tony-aq/optic
|
workspaces/cli-shared/src/diffs/trail-parsers.ts
|
<reponame>tony-aq/optic<filename>workspaces/cli-shared/src/diffs/trail-parsers.ts
import { IRequestSpecTrail } from './request-spec-trail';
import { IInteractionTrail } from './interaction-trail';
type EndpointForTrails = {
pathId: string;
method: string;
query: {
queryParametersId: string;
} | null;
requests: {
requestId: string;
contentType: string;
}[];
responses: {
responseId: string;
statusCode: number;
contentType: string;
}[];
};
export type LocationDescriptor =
| {
type: 'request';
requestId: string;
contentType: string;
}
| {
type: 'response';
responseId: string;
contentType: string;
statusCode: number;
}
| {
type: 'query';
queryParametersId: string;
}
| {
type: 'path_request';
contentType: string;
}
| {
type: 'path_response';
statusCode: number;
contentType?: string; // Content type is nullable for responses without bodies
}
| {
type: 'path_query';
};
export function locationForTrails(
trail: IRequestSpecTrail,
interactionTrail: IInteractionTrail,
endpoints: EndpointForTrails[]
): {
pathId: string;
method: string;
descriptor: LocationDescriptor;
} | null {
if ('SpecRoot' in trail) {
return null;
} else if ('SpecRequestRoot' in trail || 'SpecRequestBody' in trail) {
const { requestId } =
'SpecRequestRoot' in trail
? trail.SpecRequestRoot
: trail.SpecRequestBody;
let contentType = '';
const endpoint = endpoints.find(
(endpoint) =>
!!endpoint.requests.find((request) => {
if (request.requestId === requestId) {
contentType = request.contentType;
}
return request.requestId === requestId;
})
);
if (!endpoint) {
console.error(
`Could not find endpoint with request ${requestId} in current spec endpoints`
);
return null;
}
const { method, pathId } = endpoint;
return {
pathId: pathId,
method: method,
descriptor: {
type: 'request',
requestId,
contentType,
},
};
} else if ('SpecResponseRoot' in trail || 'SpecResponseBody' in trail) {
const { responseId } =
'SpecResponseRoot' in trail
? trail.SpecResponseRoot
: trail.SpecResponseBody;
let contentType = '';
let statusCode = 0;
const endpoint = endpoints.find(
(endpoint) =>
!!endpoint.responses.find((response) => {
if (response.responseId === responseId) {
contentType = response.contentType;
statusCode = response.statusCode;
}
return response.responseId === responseId;
})
);
if (!endpoint) {
console.error(
`Could not find endpoint with response ${responseId} in current spec endpoints`
);
return null;
}
const { pathId, method } = endpoint;
return {
pathId: pathId,
method: method,
descriptor: {
type: 'response',
statusCode: statusCode,
responseId,
contentType,
},
};
} else if ('SpecPath' in trail) {
const { pathId } = trail.SpecPath;
const method = methodForInteractionTrail(interactionTrail);
if (!method) {
console.error('method not found in SpecPath interaction trail');
return null;
}
const inRequest = inRequestForInteractionTrail(interactionTrail);
const inResponse = inResponseForInteractionTrail(interactionTrail);
if (inRequest) {
return {
pathId,
method,
descriptor: {
type: 'path_request',
contentType: inRequest.contentType,
},
};
} else if (inResponse) {
return {
pathId,
method,
descriptor: {
type: 'path_response',
contentType: inResponse.contentType,
statusCode: inResponse.statusCode,
},
};
} else {
return {
pathId,
method,
descriptor: {
type: 'path_query',
},
};
}
} else if ('SpecQueryParameters' in trail) {
const { queryParametersId } = trail.SpecQueryParameters;
const endpoint = endpoints.find(
(endpoint) =>
endpoint.query && endpoint.query.queryParametersId === queryParametersId
);
if (!endpoint) {
console.error(
`Could not find endpoint with query ${queryParametersId} in current spec endpoints`
);
return null;
}
return {
pathId: endpoint.pathId,
method: endpoint.method,
descriptor: {
type: 'query',
queryParametersId,
},
};
}
console.error(`Received an unexpected trail`, trail);
return null;
}
export function methodForInteractionTrail(
interactionTrail: IInteractionTrail
): string | undefined {
const pathComponent = interactionTrail.path.find((pathComponent) => {
return 'Method' in pathComponent;
});
if (pathComponent && 'Method' in pathComponent) {
return pathComponent.Method.method;
}
}
export function inResponseForInteractionTrail(
interactionTrail: IInteractionTrail
): { statusCode: number; contentType?: string } | undefined {
const last = interactionTrail.path[interactionTrail.path.length - 1];
if ('ResponseBody' in last) {
return last.ResponseBody;
} else if ('ResponseStatusCode' in last) {
return {
statusCode: last.ResponseStatusCode.statusCode,
};
}
}
export function inRequestForInteractionTrail(
interactionTrail: IInteractionTrail
): { contentType: string } | undefined {
const last = interactionTrail.path[interactionTrail.path.length - 1];
if ('RequestBody' in last) {
return last.RequestBody;
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/sharing/ShareButton.tsx
|
<filename>workspaces/ui-v2/src/components/sharing/ShareButton.tsx<gh_stars>100-1000
import React, { useCallback, useState } from 'react';
import {
Button,
Dialog,
DialogContent,
DialogActions,
makeStyles,
Typography,
} from '@material-ui/core';
import ShareIcon from '@material-ui/icons/Share';
import { ShareModal } from './ShareModal';
import { useAuth0 } from '@auth0/auth0-react';
import { useSpecRepository } from '<src>/contexts/SpecRepositoryContext';
import { useAppConfig } from '<src>/contexts/config/AppConfiguration';
import { useAsyncMemo } from 'use-async-memo';
import { useAnalytics } from '<src>/contexts/analytics';
import { useAppSelector } from '<src>/store';
export enum ShareTarget {
TEAM = 'team',
CONSUMER = 'consumer',
// OTHER = 'other',
}
const useStyles = makeStyles((theme) => ({
root: {
marginRight: theme.spacing(1),
height: 25,
},
}));
export const ShareButton: React.FC<{}> = (props) => {
const styles = useStyles(props);
const { getAccessTokenSilently, isAuthenticated } = useAuth0();
const specRepo = useSpecRepository();
const {
backendApi: { domain: baseDomain },
sharing,
} = useAppConfig();
const specId = useAppSelector(
(state) => state.metadata.data?.specificationId!
);
const analytics = useAnalytics();
const personId = useAsyncMemo(async () => {
if (isAuthenticated) {
const token = await getAccessTokenSilently();
const response = await fetch(`${baseDomain}/api/person`, {
headers: { Authorization: `Bearer ${token}` },
});
const resp_data = await response.json();
analytics.userLoggedIn(resp_data.id);
return resp_data.id;
}
}, [getAccessTokenSilently, isAuthenticated, baseDomain, analytics]);
const share = useCallback(
async (target: ShareTarget) => {
const token = await getAccessTokenSilently();
let newSpecResp = await fetch(
`${baseDomain}/api/person/public-specs-v3`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'content-type': 'application/json',
},
body: JSON.stringify({
metadata: {
sharing_context: {
local_ui_v1: {
with: target.toString(),
},
},
},
analytics_id: specId,
}),
}
);
if (!newSpecResp.ok) {
throw new Error(
`Error creating spec to upload: ${
newSpecResp.statusText
}: ${await newSpecResp.text()}`
);
} else {
let { upload_url, id: newSpecId } = await newSpecResp.json();
let uploadResult = await fetch(upload_url, {
method: 'PUT',
headers: {
'x-amz-server-side-encryption': 'AES256',
},
body: JSON.stringify(await specRepo.listEvents()),
});
if (!uploadResult.ok) {
throw new Error(
`Error uploading spec: ${
uploadResult.statusText
}: ${await uploadResult.text()}`
);
}
analytics.userShared(target, newSpecId);
if (target === ShareTarget.TEAM) {
return `${
sharing.enabled && sharing.specViewerDomain
}/people/${personId}/public-specs/${newSpecId}/documentation?demo=true`;
} else {
return `${
sharing.enabled && sharing.specViewerDomain
}/people/${personId}/public-specs/${newSpecId}/documentation`;
}
}
},
[
getAccessTokenSilently,
specRepo,
baseDomain,
personId,
specId,
sharing,
analytics,
]
);
const [isOpen, setIsOpen] = useState(false);
return (
<div
style={{
marginRight: 5,
opacity: 0.45,
display: 'flex',
flexDirection: 'row',
}}
>
<Button
variant="outlined"
className={styles.root}
onClick={() => {
analytics.userStartedSharing();
setIsOpen(true);
}}
>
<Typography variant="body2" style={{ textTransform: 'none' }}>
Share
</Typography>
<ShareIcon style={{ marginLeft: 3, height: 14 }} />
</Button>
<Dialog
open={isOpen}
onClose={() => setIsOpen(false)}
fullWidth
maxWidth="sm"
>
<DialogContent>
<ShareModal share={share} />
</DialogContent>
<DialogActions>
<Button onClick={() => setIsOpen(false)} autoFocus>
Cancel
</Button>
</DialogActions>
</Dialog>
</div>
);
};
|
tony-aq/optic
|
workspaces/ui-v2/src/components/layouts/FullWidth.tsx
|
<filename>workspaces/ui-v2/src/components/layouts/FullWidth.tsx
import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Container } from '@material-ui/core';
export function FullWidth(props: any) {
const classes = useStyles();
return (
<Container maxWidth="lg" className={classes.wrapper} {...props}>
{props.children}
</Container>
);
}
const useStyles = makeStyles((theme) => ({
wrapper: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
paddingLeft: 15,
paddingRight: 15,
},
}));
|
tony-aq/optic
|
workspaces/cli-shared/test/tests/diff-worker-rust.ts
|
// Getting the Typescript compiler to find these in cli-shared/typings through
// passing it a tsconfig has been successful :(
/// <reference types="../../typings/stream-chain/index" />
/// <reference types="../../typings/stream-json/index" />
import Tap from 'tap';
import { FileSystemAvroCaptureSaver as CaptureSaver } from '@useoptic/cli-shared';
import { IHttpInteraction as Interaction } from '@useoptic/optic-domain';
import { exampleInteractions } from '../fixtures/interactions';
import Path from 'path';
import Fs from 'fs-extra';
import { Readable, Transform, TransformCallback } from 'stream';
import { InteractionDiffWorkerRust } from '../../src/diffs/interaction-diff-worker-rust';
Tap.test('diff-worker-rust', async (test) => {
await test.test('can diff a capture against a spec', async (t) => {
const diffConfig = await prepare(
exampleInteractions(100),
Path.join(__dirname, '..', 'fixtures', 'example-events.json')
);
const worker = new InteractionDiffWorkerRust({
...diffConfig,
events: await Fs.readJson(diffConfig.specFilePath),
ignoreRules: await Fs.readJson(diffConfig.ignoreRequestsFilePath),
});
const output = await worker.run();
const streamToString = new Transform({
writableObjectMode: true,
readableObjectMode: false,
transform(chunk: any, encoding: string, callback: TransformCallback) {
callback(null, JSON.stringify(chunk) + '\n');
},
});
Readable.from(output.results).pipe(streamToString).pipe(process.stdout);
});
// await test.test(
// 'will propagate errors in parsing spec from the diff engine',
// async (t) => {
// const diffConfig = await prepare(
// exampleInteractions(10),
// // this will fail, because interactions aren't a valid spec file
// Path.join(__dirname, '..', 'fixtures', 'example-interaction.json')
// );
//
// const worker = new DiffWorkerRust(diffConfig);
// const rejecting = t.rejects(
// new Promise((_, reject) => {
// worker.events.once('error', reject);
// })
// );
// await worker.start();
//
// await rejecting;
// }
// );
//
// await test.test(
// 'will propagate errors in diffing an interaction from the diff engine',
// async (t) => {
// const specPath = Path.join(
// __dirname,
// '..',
// 'fixtures',
// 'unsupported-reference-base-shapes',
// 'events.json'
// );
// const interactionPath = Path.join(
// __dirname,
// '..',
// 'fixtures',
// 'unsupported-reference-base-shapes',
// 'interaction.json'
// );
//
// const diffConfig = await prepare(
// exampleInteractions(1, interactionPath),
// specPath
// );
//
// const worker = new DiffWorkerRust(diffConfig);
// const rejecting = t.rejects(
// new Promise((_, reject) => {
// worker.events.once('error', reject);
// })
// );
//
// await worker.start();
// await rejecting;
// }
// );
});
async function prepare(
interactions: AsyncIterable<Interaction>,
eventsPath: string,
diffId: string = 'test-diff'
) {
if (!Fs.existsSync(eventsPath)) {
throw new Error(
'eventsPath must be valid path to spec events file to prepare a diff for the diff-worker test'
);
}
const captureBaseDirectory = __dirname;
const captureId = 'diff-worker-test-capture';
await Fs.emptyDir(Path.join(captureBaseDirectory, captureId));
const captureSaver = new CaptureSaver({
captureBaseDirectory,
captureId,
});
await captureSaver.init();
for await (let interaction of interactions) {
captureSaver.save(interaction);
}
await captureSaver.cleanup();
// prepare output
const outputBaseDir = Path.join(captureBaseDirectory, captureId, 'diffs');
const outputDir = Path.join(outputBaseDir, diffId);
if (Fs.existsSync(outputBaseDir)) {
Fs.removeSync(outputBaseDir);
}
Fs.mkdirpSync(Path.join(outputDir));
Fs.copySync(
Path.join(__dirname, '..', 'fixtures', 'diff-worker-output-base'),
outputDir
);
Fs.copyFileSync(eventsPath, Path.join(outputDir, 'events.json'));
const diffConfig = {
captureId,
captureBaseDirectory,
diffId,
specFilePath: Path.join(outputDir, 'events.json'),
ignoreRequestsFilePath: Path.join(outputDir, 'ignoreRequests.json'),
additionalCommandsFilePath: Path.join(outputDir, 'additionalCommands.json'),
filtersFilePath: Path.join(outputDir, 'filters.json'),
};
return diffConfig;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/loaders/Errors.tsx
|
import React from 'react';
import { CenteredColumn } from '../layouts/CenteredColumn';
import { makeStyles } from '@material-ui/styles';
import { Box, Typography } from '@material-ui/core';
import { ErrorOutline as ErrorOutlineIcon } from '@material-ui/icons';
export function FullPageError({ errorMessage }: { errorMessage?: string }) {
const classes = useStyles();
return (
<CenteredColumn maxWidth="md">
<div className={classes.center}>
<Box display="flex">
<ErrorOutlineIcon fontSize="large" />
<Typography
variant="h6"
color="textSecondary"
className={classes.text}
>
{errorMessage || 'There was an error loading the page'}
</Typography>
</Box>
</div>
</CenteredColumn>
);
}
const useStyles = makeStyles((theme) => ({
center: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: 'calc(100vh - 40px)',
},
text: {
marginLeft: 10,
marginTop: -1,
fontFamily: 'Ubuntu Mono',
},
}));
|
tony-aq/optic
|
workspaces/spectacle/test/utils.ts
|
import * as fs from 'fs';
export function loadEvents(file: string) {
return JSON.parse(fs.readFileSync(file).toString('utf-8'));
}
|
tony-aq/optic
|
workspaces/cli-config/src/human-readable-ids.d.ts
|
declare module 'human-readable-ids' {
type ExportedRandom = {
random: () => string;
};
export const hri = ExportedRandom;
export const humanReadableIds = ExportedRandom;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/types/endpoints.ts
|
<filename>workspaces/ui-v2/src/types/endpoints.ts
import { ChangeType } from './changes';
export interface IPathParameter {
id: string;
name: string;
isParameterized: boolean;
description: string;
endpointId: string;
}
export interface IPath {
absolutePathPattern: string;
parentPathId: string | null;
absolutePathPatternWithParameterNames: string;
isParameterized: boolean;
name: string;
pathId: string;
}
export interface IEndpoint {
id: string;
pathId: string;
method: string;
purpose: string;
description: string;
fullPath: string;
pathParameters: IPathParameter[];
isRemoved: boolean;
query: IQueryParameters | null;
requests: IRequest[];
// Grouped by status code
responsesByStatusCode: Record<string, IResponse[]>;
}
export interface IEndpointWithChanges extends IEndpoint {
changes: ChangeType | null;
}
export interface IQueryParameters {
queryParametersId: string;
rootShapeId: string;
isRemoved: boolean;
description: string;
endpointId: string;
pathId: string;
method: string;
}
export interface IRequest {
requestId: string;
description: string;
endpointId: string;
pathId: string;
method: string;
isRemoved: boolean;
body: IBody | null;
}
export interface IResponse {
responseId: string;
statusCode: number;
endpointId: string;
pathId: string;
method: string;
description: string;
isRemoved: boolean;
body: IBody | null;
}
export interface IBody {
contentType: string;
rootShapeId: string;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/utils/findLongestCommonPath.ts
|
export function findLongestCommonPath(paths: string[][]): string {
if (paths.length === 0) return '/';
let match: string[] = [];
// sorted paths by lengths ascending
const sortedPaths = paths
.concat()
.sort((a, b) => (a.length - b.length > 0 ? 1 : -1));
const shortestPath = sortedPaths[0];
const otherPaths = sortedPaths.slice(1);
for (let i = 0; i < shortestPath.length; i++) {
if (!otherPaths.every((path) => path[i] === shortestPath[i])) {
break;
}
match.push(shortestPath[i]);
}
return match.join('/');
}
|
tony-aq/optic
|
workspaces/analytics/tests/EventBus.test.ts
|
import { newAnalyticsEventBus } from '../src/eventbus';
import { CliClientContext } from '../src/interfaces/TrackingEventBase';
import { UserLoggedInFromCLI } from '../src/cliEvents';
const getContext: (batchId: string) => Promise<CliClientContext> = async () => {
return {
clientId: 'testing',
platform: 'furby',
arch: 'mips',
release: '1998',
apiName: 'testingApiName',
clientSessionInstanceId: 'testing',
clientTimestamp: 'testingTime',
clientAgent: 'testingAgent',
source: 'user',
};
};
test('Event Bus can listen for analytics events', async (done) => {
const bus = newAnalyticsEventBus(getContext);
new Promise((resolve) => {
bus.listen((e) => {
expect(e).toMatchSnapshot();
resolve(null);
});
}).then(done);
bus.emit(UserLoggedInFromCLI({ userId: 'hello' }));
});
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelog/components/ValidateBatchId.tsx
|
<filename>workspaces/ui-v2/src/pages/changelog/components/ValidateBatchId.tsx
import React, { FC } from 'react';
import { Redirect } from 'react-router-dom';
import { useBatchCommits } from '<src>/hooks/useBatchCommits';
import { useDocumentationPageLink } from '<src>/components/navigation/Routes';
export const ValidateBatchId: FC<{ batchId: string }> = ({
children,
batchId,
}) => {
const allBatchCommits = useBatchCommits();
const documentationPageLink = useDocumentationPageLink();
const validBatchId = allBatchCommits.batchCommits.some(
(i) => i.batchId === batchId
);
if (allBatchCommits.loading) {
return null;
}
if (!validBatchId) {
return <Redirect to={documentationPageLink.linkTo()} />;
}
return <>{children}</>;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelogHistory/index.ts
|
export * from './ChangelogHistory';
|
tony-aq/optic
|
workspaces/ui-v2/src/utils/index.ts
|
<reponame>tony-aq/optic
export * from './dateFormat';
export * from './endpoint-utilities';
export * from './go-to-anchor';
export * from './findLongestCommonPath';
export * from './pathMatcher';
|
tony-aq/optic
|
workspaces/ui-v2/src/store/shapes/types.ts
|
import { JsonType } from '@useoptic/optic-domain';
import { ChangeType } from '<src>/types';
export type ShapeId = string;
export type ReduxField = {
fieldId: string;
name: string;
shapeId: string;
changes: ChangeType | null;
contributions: Record<string, string>;
};
export type ReduxShape =
| {
shapeId: string;
jsonType: JsonType.OBJECT;
asArray?: undefined;
asObject: {
fields: ReduxField[];
};
}
| {
shapeId: string;
jsonType: JsonType.ARRAY;
asArray: {
shapeId: string;
};
asObject?: undefined;
}
| {
shapeId: string;
jsonType: Exclude<JsonType, JsonType.OBJECT | JsonType.ARRAY>;
asArray?: undefined;
asObject?: undefined;
};
|
tony-aq/optic
|
workspaces/snapshot-tests/src/tasks/RfcStateAndInteractionsToDiffs/index.ts
|
import {
ITaskExecutor,
ITaskExecutorDependencies,
ITaskExecutorOutput,
ITaskSpecification,
ITaskSpecificationInputs,
TaskType,
} from '../';
import {
InteractionsFileToJsTaskOutput,
InteractionsFileToJsTaskSpecification,
} from '../InteractionsFileToJs';
import {
EventsFileToJsTaskOutput,
EventsFileToJsTaskSpecification,
} from '../EventsFileToJsTaskSpecification';
import * as opticEngine from '@useoptic/optic-engine-wasm';
export const interactionsFromFileKey = 'interactionsFromFile';
export const eventsFromFileKey = 'eventsFromFile';
export interface RfcStateAndInteractionsToDiffsTaskDependencies
extends ITaskExecutorDependencies {
[interactionsFromFileKey]: InteractionsFileToJsTaskOutput;
[eventsFromFileKey]: EventsFileToJsTaskOutput;
}
export interface RfcStateAndInteractionsToDiffsTaskInputs
extends ITaskSpecificationInputs {
[interactionsFromFileKey]: InteractionsFileToJsTaskSpecification;
[eventsFromFileKey]: EventsFileToJsTaskSpecification;
}
export interface IHttpInteractionsGroupedByDiff {}
export interface RfcStateAndInteractionsToDiffsTaskOutput
extends ITaskExecutorOutput {
diffs: IHttpInteractionsGroupedByDiff;
}
export interface RfcStateAndInteractionsToDiffsTaskSpecification
extends ITaskSpecification {
type: TaskType.RfcStateAndInteractionsToDiffs;
inputs: RfcStateAndInteractionsToDiffsTaskInputs;
}
export const buildDiffsFromRfcStateAndInteractions: ITaskExecutor<
RfcStateAndInteractionsToDiffsTaskSpecification,
RfcStateAndInteractionsToDiffsTaskDependencies,
RfcStateAndInteractionsToDiffsTaskOutput
> = async function (taskSpecification, dependencies) {
debugger;
const rfcState = dependencies[eventsFromFileKey].events;
const interactions = dependencies[interactionsFromFileKey].interactions;
const events = dependencies[eventsFromFileKey].events;
const spec = opticEngine.spec_from_events(JSON.stringify(events));
const diffs = interactions.flatMap((interaction) => {
const interactionDiffs = opticEngine.diff_interaction(
JSON.stringify(interaction),
spec,
{}
);
return JSON.parse(interactionDiffs);
});
return {
diffs,
};
};
|
tony-aq/optic
|
workspaces/cli-shared/src/diffs/initial-types.ts
|
import { IJsonTrail } from './json-trail';
import { LearningResults } from '@useoptic/optic-domain';
export type ILearnedBodies = LearningResults.UndocumentedEndpointBodies.LearnedBodies;
export type ILearnedBody = LearningResults.UndocumentedEndpointBodies.LearnedBody;
export type ILearnedQueryParameters = LearningResults.UndocumentedEndpointBodies.LearnedQueryParameters;
export interface IAffordanceTrails {
affordances: IAffordance[];
interactions: IAffordanceInteractionPointers;
}
export interface IAffordanceTrailsDiffHashMap {
[key: string]: IAffordanceTrails;
}
export interface IAffordance {
trail: IJsonTrail;
wasString: boolean;
wasNumber: boolean;
wasBoolean: boolean;
wasNull: boolean;
wasArray: boolean;
wasObject: boolean;
fieldSet: string[][];
}
export interface IAffordanceInteractionPointers {
wasString: string[];
wasNumber: string[];
wasBoolean: string[];
wasNull: string[];
wasArray: string[];
wasObject: string[];
wasMissing: string[];
wasEmptyArray: string[];
wasStringTrails: { [key: string]: IJsonTrail[] };
wasNumberTrails: { [key: string]: IJsonTrail[] };
wasBooleanTrails: { [key: string]: IJsonTrail[] };
wasNullTrails: { [key: string]: IJsonTrail[] };
wasArrayTrails: { [key: string]: IJsonTrail[] };
wasObjectTrails: { [key: string]: IJsonTrail[] };
wasMissingTrails: { [key: string]: IJsonTrail[] };
wasEmptyArrayTrails: { [key: string]: IJsonTrail[] };
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/selectors/shapeSelectors.ts
|
<reponame>tony-aq/optic
import { SerializedError } from '@reduxjs/toolkit';
import * as Sentry from '@sentry/react';
import sortBy from 'lodash.sortby';
import { JsonType } from '@useoptic/optic-domain';
import {
AsyncStatus,
IShapeRenderer,
IFieldDetails,
QueryParameters,
} from '<src>/types';
import { RootState } from '../root';
export const getShapeRenderer = (rootShapeId: string) => (
state: RootState
): AsyncStatus<IShapeRenderer[], SerializedError> => {
const shapeState = state.shapes.rootShapes[rootShapeId];
if (!shapeState || shapeState.loading) {
return {
loading: true,
};
} else if (shapeState.error) {
return {
loading: false,
error: shapeState.error,
};
}
const resolveShape = (shapeId: string): IShapeRenderer[] => {
const reduxShapes = state.shapes.shapeMap[shapeId];
if (!reduxShapes || reduxShapes.length === 0) {
console.error(`Could not find shape ${shapeId} in redux store`);
Sentry.captureEvent({
message: 'Could not find shape in redux store',
extra: {
shapes: state.shapes,
},
});
return [];
}
return reduxShapes.map(
(reduxShape): IShapeRenderer => {
if (reduxShape.jsonType === JsonType.OBJECT) {
return {
...reduxShape,
asObject: {
fields: reduxShape.asObject.fields.map((field) => {
const shapeChoices = resolveShape(field.shapeId);
const required = !shapeChoices.some(
(i) => i.jsonType === JsonType.UNDEFINED
);
return {
...field,
shapeChoices: sortBy(
shapeChoices.filter(
(shapeChoice) =>
shapeChoice.jsonType !== JsonType.UNDEFINED
),
(shapeChoice) => shapeChoice.jsonType === JsonType.NULL
),
required,
};
}),
},
};
} else if (reduxShape.jsonType === JsonType.ARRAY) {
return {
...reduxShape,
asArray: {
shapeId: reduxShape.asArray.shapeId,
shapeChoices: resolveShape(reduxShape.asArray.shapeId),
},
};
} else {
return {
...reduxShape,
};
}
}
);
};
return {
loading: false,
data: resolveShape(rootShapeId),
};
};
export function createFlatList(
shapes: IShapeRenderer[],
endpointId: string,
depth: number = 0
): IFieldDetails[] {
const fieldDetails: IFieldDetails[] = [];
shapes.forEach((shape) => {
if (shape.asObject) {
shape.asObject.fields.forEach((field) => {
fieldDetails.push({
fieldId: field.fieldId,
name: field.name,
contribution: {
id: field.fieldId,
contributionKey: 'description',
value: field.contributions.description || '',
endpointId: endpointId,
},
depth,
shapes: field.shapeChoices,
required: field.required,
});
fieldDetails.push(
...createFlatList(field.shapeChoices, endpointId, depth + 1)
);
});
}
if (shape.asArray) {
fieldDetails.push(
...createFlatList(shape.asArray.shapeChoices, endpointId, depth + 1)
);
}
});
return fieldDetails;
}
export const removeArrayShapeFromField = (
field: IFieldDetails
): IFieldDetails => {
const isArray = !!field.shapes.find(
(choice) => choice.jsonType === JsonType.ARRAY
);
const hasMultipleShapes = field.shapes.length > 1;
return {
...field,
shapes:
isArray && hasMultipleShapes
? field.shapes.filter((choice) => choice.jsonType === JsonType.ARRAY)
: field.shapes,
};
};
export const convertShapeToQueryParameters = (
shapes: IShapeRenderer[]
): QueryParameters => {
const queryParameters: QueryParameters = {};
if (shapes.length !== 1 || !shapes[0].asObject) {
if (shapes.length > 1) {
console.error('unexpected format for query parameters');
}
// otherwise loading
return {};
}
for (const field of shapes[0].asObject.fields) {
let isArray = field.shapeChoices.findIndex(
(choice) => choice.jsonType === JsonType.ARRAY
);
if (isArray > -1) {
field.additionalAttributes = ['multiple'];
if (field.shapeChoices.length > 1) {
field.shapeChoices.splice(isArray, 1);
} else {
field.shapeChoices = field.shapeChoices[isArray].asArray!.shapeChoices;
}
}
queryParameters[field.name] = field;
}
return queryParameters;
};
|
tony-aq/optic
|
workspaces/api-checks/src/spectacle.ts
|
import fs from 'fs';
import { InMemoryOpticContextBuilder } from '@useoptic/spectacle/build/in-memory';
import OpticEngine from '@useoptic/optic-engine-wasm';
import { makeSpectacle } from '@useoptic/spectacle';
export class Spectacle {
constructor(public spectacle: any) {}
static async fromFile(filename: string) {
const events = JSON.parse(fs.readFileSync(filename).toString());
return await Spectacle.fromEvents(events);
}
static async fromEvents(events: any[]) {
const initialOpticContext = await InMemoryOpticContextBuilder.fromEvents(
OpticEngine,
events
);
const spectacle = await makeSpectacle(initialOpticContext);
return new Spectacle(spectacle);
}
async getEndpointChanges(sinceBatchCommitId: string) {
return await this.spectacle.queryWrapper({
query: `query GetEndpointChanges($sinceBatchCommitId: String!) {
endpointChanges(sinceBatchCommitId: $sinceBatchCommitId) {
endpoints {
change {
category
}
pathId
path
method
}
}
}`,
variables: { sinceBatchCommitId },
});
}
async getMatchingRequest(endpointChange: any) {
return (
await this.spectacle.queryWrapper({
query: `{
requests {
absolutePathPatternWithParameterNames
method
pathId
responses {
id
statusCode
}
}
}`,
variables: {},
})
).data.requests.find(
(request: any) =>
request.pathId === endpointChange.pathId &&
request.method === endpointChange.method
);
}
async getBatchCommits() {
return await this.spectacle.queryWrapper({
query: `{
batchCommits {
createdAt
batchId
}
}`,
variables: {},
});
}
}
export async function getSinceBatchCommitId(
specFilename: string
): Promise<string> {
const baseSpec = JSON.parse(fs.readFileSync(specFilename).toString());
const spectacle = await Spectacle.fromEvents(baseSpec);
const batchCommitResults = await spectacle.getBatchCommits();
return batchCommitResults.data?.batchCommits?.reduce(
(result: any, batchCommit: any) => {
return batchCommit.createdAt > result.createdAt ? batchCommit : result;
}
).batchId as string;
}
|
tony-aq/optic
|
workspaces/cli-shared/src/command-session.ts
|
import { ChildProcess, spawn, SpawnOptions } from 'child_process';
import { EventEmitter } from 'events';
import treeKill from 'tree-kill';
import { developerDebugLogger } from './index';
export interface ICommandSessionConfig {
command: string;
environmentVariables: NodeJS.ProcessEnv;
}
class CommandSession {
public exitCode: number | null = null;
private child?: ChildProcess;
private isRunning: boolean = false;
public events: EventEmitter = new EventEmitter();
start(config: ICommandSessionConfig, silent: boolean = false) {
const taskOptions: SpawnOptions = {
env: {
...process.env,
...config.environmentVariables,
},
shell: true,
cwd: process.cwd(),
stdio: silent ? 'ignore' : 'inherit',
};
this.isRunning = true;
this.child = spawn(config.command, taskOptions);
this.events.once('stopped', (e) => {
this.isRunning = false;
});
this.child.on('exit', (code, signal) => {
this.exitCode = code;
developerDebugLogger(
`command process exited with code ${code} and signal ${signal}`
);
this.events.emit('stopped', { state: code ? 'failed' : 'completed' });
});
return this.child;
}
stop() {
if (this.isRunning && this.child) {
const pid = this.child.pid;
return new Promise<void>((resolve) => {
treeKill(pid, (e) => {
if (e) {
developerDebugLogger(`Issue killing child process: ${e}`);
}
this.events.emit('stopped', { state: 'terminated' });
resolve();
});
});
}
}
}
export { CommandSession };
|
tony-aq/optic
|
workspaces/local-cli/src/commands/init.ts
|
import { Command, flags } from '@oclif/command';
import { createFileTree, getPathsRelativeToConfig } from '@useoptic/cli-config';
import colors from 'colors';
import cli from 'cli-ux';
import fs from 'fs-extra';
import path from 'path';
import { developerDebugLogger, fromOptic } from '@useoptic/cli-shared';
import { trackUserEvent } from '../shared/analytics';
import * as opticEngine from '@useoptic/optic-engine-wasm';
import { ApiInitializedInProject } from '@useoptic/analytics';
import { buildTask } from '@useoptic/cli-config/build/helpers/initial-task';
import { ensureDaemonStarted } from '@useoptic/cli-server';
import { lockFilePath } from '../shared/paths';
import { Config } from '../config';
import { Client } from '@useoptic/cli-client';
import openBrowser from 'react-dev-utils/openBrowser';
import { linkToSetup } from '../shared/ui-links';
import { LocalCliSpectacle } from '@useoptic/spectacle-shared';
export default class Init extends Command {
static description = 'add Optic to your API';
static flags = {
inboundUrl: flags.string({}),
targetUrl: flags.string({}),
command: flags.string({}),
};
async run() {
const cwd = process.cwd();
const { flags } = this.parse(Init);
if (
fs.existsSync(path.join(cwd, 'optic.yml')) &&
Object.entries(flags).length === 0
) {
return this.log(
colors.red(
`This directory already has an ${colors.bold('optic.yml')} file.\r\n`
),
colors.yellow(
`You can see the current documentation for this project with ${colors.bold(
'api spec'
)}.`
)
);
}
const shouldUseThisDirectory = await cli.confirm(
`${colors.bold.blue(cwd)}\nIs this your API's root directory? (yes/no)`
);
if (!shouldUseThisDirectory) {
this.log(
colors.red(
`Optic must be initialized in your API's root directory. Change your working directory and then run ${colors.bold(
'api init'
)} again`
)
);
process.exit(1);
}
const name = await cli.prompt('What is this API named?');
//bring me back with an ID please
// await trackAndSpawn('New API Created', { name });
const config = buildTask(
name,
flags,
flags.inboundUrl && flags.targetUrl ? 'start-proxy' : 'start'
);
// const token: string = await Promise.resolve('token-from-backend')
const { configPath } = await createFileTree(config, cwd);
cli.log(
fromOptic(`Added Optic configuration to ${colors.bold(configPath)}`)
);
async function startInitFlow() {
const paths = await getPathsRelativeToConfig();
const daemonState = await ensureDaemonStarted(
lockFilePath,
Config.apiBaseUrl
);
const apiBaseUrl = `http://localhost:${daemonState.port}/api`;
developerDebugLogger(`api base url: ${apiBaseUrl}`);
const cliClient = new Client(apiBaseUrl);
const cliSession = await cliClient.findSession(paths.cwd, null, null);
developerDebugLogger({ cliSession });
openBrowser(linkToSetup(cliSession.session.id));
const spectacle = new LocalCliSpectacle(
`${apiBaseUrl}/specs/${cliSession.session.id}`,
opticEngine
);
const requestQuery = await spectacle.query<any>({
query: `{
metadata {
id
}
}`,
variables: {},
});
return requestQuery?.data?.metadata?.id ?? 'anon-spec-id';
}
const specId = await startInitFlow();
await trackUserEvent({
apiName: name,
specId,
event: ApiInitializedInProject({
cwd: cwd,
source:
Object.entries(flags).length === 0
? 'documentation'
: 'on-boarding-flow',
apiName: name,
}),
});
process.exit(0);
}
}
|
tony-aq/optic
|
workspaces/cli-server/src/tasks/on-demand-trail-values-rust.ts
|
<reponame>tony-aq/optic
import {
ShapeDiffAffordancesWorker,
ShapeDiffAffordancesConfig,
ShapeDiffAffordances,
} from '@useoptic/cli-shared/build/diffs/trail-values-worker-rust';
export { ShapeDiffAffordances };
export class OnDemandShapeDiffAffordancesRust {
private worker: ShapeDiffAffordancesWorker;
constructor(config: ShapeDiffAffordancesConfig) {
this.worker = new ShapeDiffAffordancesWorker(config);
}
async run(): Promise<{ [fingerprint: string]: ShapeDiffAffordances }> {
return this.worker.run();
}
}
|
tony-aq/optic
|
workspaces/optic-domain/src/index.ts
|
export * as AsyncTools from './async-tools';
export * as Streams from './streams';
export * as Commands from './commands';
export * as Shapes from './shapes';
export * as Interactions from './interactions';
export * from './commands';
export * from './shapes';
export * from './interactions';
export * from './streams';
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ShapeRenderer/OneOfTabs.tsx
|
import * as React from 'react';
import makeStyles from '@material-ui/styles/makeStyles';
import { useSharedStyles } from './SharedStyles';
import classNames from 'classnames';
import { useShapeRenderContext } from './ShapeRenderContext';
export type OneOfTabsProps = {
choices: { label: string; id: string }[];
shapeId: string;
};
export function OneOfTabs(oneOfTabsProps: OneOfTabsProps) {
const classes = useStyles();
const { getChoice, updateChoice } = useShapeRenderContext();
const current = getChoice(oneOfTabsProps);
return (
<div className={classes.tabs}>
{oneOfTabsProps.choices.map((i, index) => (
<Choice
key={index}
{...i}
active={current === i.id}
setActive={() => {
updateChoice(oneOfTabsProps.shapeId, i.id);
}}
/>
))}
</div>
);
}
export type ChoiceTabsProps = {
choices: { label: string; id: string }[];
value: string;
setValue: (value: string) => void;
};
export function ChoiceTabs(props: ChoiceTabsProps) {
const classes = useStyles();
return (
<div className={classes.tabs}>
{props.choices.map((i, index) => (
<Choice
key={index}
{...i}
active={props.value === i.id}
setActive={() => props.setValue(i.id)}
/>
))}
</div>
);
}
function Choice({
label,
id,
active,
setActive,
}: {
label: string;
id: string;
active: boolean;
setActive: () => void;
}) {
const sharedClasses = useSharedStyles();
const classes = useStyles();
return (
<span
onClick={setActive}
className={classNames(sharedClasses.shapeFont, classes.choice, {
[classes.active]: active,
})}
>
{label}{' '}
</span>
);
}
export function ChoiceSwitch({
label,
active,
setActive,
}: {
label: string;
active: boolean;
setActive: () => void;
}) {
const sharedClasses = useSharedStyles();
const classes = useStyles();
return (
<span
onClick={setActive}
className={classNames(sharedClasses.shapeFont, classes.choice, {
[classes.active]: active,
})}
>
{label}{' '}
</span>
);
}
const useStyles = makeStyles((theme) => ({
tabs: {
display: 'flex',
},
choice: {
marginRight: 8,
textTransform: 'none',
cursor: 'pointer',
color: '#99a0ae',
'&:hover': {
color: '#73819b',
fontWeight: 700,
},
},
active: {
fontWeight: 900,
color: '#73819b',
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/store/metadata.ts
|
<gh_stars>100-1000
import {
createAsyncThunk,
createSlice,
SerializedError,
} from '@reduxjs/toolkit';
import { v4 as uuidv4 } from 'uuid';
import * as Sentry from '@sentry/react';
import { Client } from '@useoptic/cli-client';
import {
IOpticConfigRepository,
IForkableSpectacle,
} from '@useoptic/spectacle';
import { AsyncStatus } from '<src>/types';
const fetchMetadata = createAsyncThunk(
'FETCH_METADATA',
async ({
configRepository,
spectacle,
}: {
configRepository: IOpticConfigRepository;
spectacle: IForkableSpectacle;
}) => {
const client = new Client('/api');
const apiNamePromise = configRepository.getApiName().catch(() => '');
const clientAgentPromise = client
.getIdentity()
.then((response) => response.json())
.then(({ anonymousId }) => anonymousId)
.catch(() => 'anon_id');
const specMetadataPromise = spectacle
.query<{
metadata: {
id: string;
};
}>({
query: `{
metadata {
id
}
}`,
variables: {},
})
.then((result) => {
if (!result.data) {
throw new Error('Could not fetch spec metadata');
}
return result.data.metadata.id;
});
try {
const [apiName, clientAgent, specificationId] = await Promise.all([
apiNamePromise,
clientAgentPromise,
specMetadataPromise,
]);
return {
apiName,
clientAgent,
specificationId,
sessionId: uuidv4(),
};
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
}
);
const initialState = {
loading: true,
} as AsyncStatus<
{
apiName: string;
clientAgent: string;
specificationId: string;
sessionId: string;
},
SerializedError
>;
const metadataSlice = createSlice({
name: 'metadata',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchMetadata.fulfilled, (state, action) => {
return {
loading: false,
data: action.payload,
};
});
builder.addCase(fetchMetadata.rejected, (state, action) => {
return {
loading: false,
error: action.error,
};
});
},
});
export const actions = {
...metadataSlice.actions,
fetchMetadata,
};
export const reducer = metadataSlice.reducer;
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelog/components/ChangelogAccessoryNavigation.tsx
|
<reponame>tony-aq/optic
import React from 'react';
import { ChangesSinceDropdown } from '<src>/pages/changelog/components/ChangelogDropdown';
export function ChangelogPageAccessoryNavigation() {
return (
<div style={{ paddingRight: 10, display: 'flex', flexDirection: 'row' }}>
<ChangesSinceDropdown />
</div>
);
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelogHistory/components/index.ts
|
<filename>workspaces/ui-v2/src/pages/changelogHistory/components/index.ts
export * from './ConfirmResetModal';
|
tony-aq/optic
|
workspaces/ui-v2/src/components/HighlightController.tsx
|
import React, { FC, useState } from 'react';
type HighlightControllerProps = {
children: (
selectedItem: string | null,
setSelectedItem: (selectedItem: string | null) => void
) => React.ReactElement;
};
export const HighlightController: FC<HighlightControllerProps> = ({
children,
}) => {
const [selectedItem, setSelectedItem] = useState<string | null>(null);
return <>{children(selectedItem, setSelectedItem)}</>;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/hooks/util/useDebouncedFn.ts
|
import { useMemo } from 'react';
import debounce from 'lodash.debounce';
export const useDebouncedFn = <T extends (...args: any) => any>(
fn: T,
ms: number
) => {
return useMemo(() => debounce(fn, ms), [fn, ms]);
};
|
tony-aq/optic
|
workspaces/api-checks/src/runner.ts
|
import path from 'path';
import { Spectacle } from './spectacle';
import {
CheckFunction,
EndpointChangeChecksOptions,
CheckFunctionRegistry,
} from './types';
export class EndpointChangeChecks {
public sinceBatchCommitId: string;
public spectacle: any;
public checks: CheckFunctionRegistry = {
added: [],
updated: [],
removed: [],
};
constructor({ sinceBatchCommitId, spectacle }: EndpointChangeChecksOptions) {
this.sinceBatchCommitId = sinceBatchCommitId;
this.spectacle = spectacle;
}
static async withSpectacle(
specFilename: string,
options: { sinceBatchCommitId: string }
) {
const spectacle = await Spectacle.fromFile(path.join('..', specFilename));
return new EndpointChangeChecks({ ...options, spectacle });
}
on(action: keyof CheckFunctionRegistry, check: CheckFunction) {
this.checks[action].push(check);
return this; // for chaining
}
async run() {
const endpointChangesQuery = await this.spectacle.getEndpointChanges(
this.sinceBatchCommitId
);
const checkResults = new CheckResults();
for (const endpointChange of endpointChangesQuery.data.endpointChanges
.endpoints) {
const matchingRequest = await this.spectacle.getMatchingRequest(
endpointChange
);
for (const check of this.checks[
endpointChange.change.category as keyof CheckFunctionRegistry
]) {
const checkResult = await check({
endpointChange,
// We pass this in as endpoint because in the context of a check the name makes more sense
endpoint: matchingRequest,
});
checkResults.handleResult(checkResult);
}
}
return checkResults;
}
}
export class CheckResults {
constructor(public results: string[] = []) {}
all() {
return this.results;
}
handleResult(result?: string) {
if (result) this.results.push(result);
}
hasFailures() {
return Boolean(this.results.length);
}
}
|
tony-aq/optic
|
workspaces/local-cli/src/commands/ingest/s3.ts
|
<reponame>tony-aq/optic<filename>workspaces/local-cli/src/commands/ingest/s3.ts<gh_stars>100-1000
import { Command, flags } from '@oclif/command';
import { ensureDaemonStarted } from '@useoptic/cli-server';
import { ingestS3 } from '@useoptic/cli-shared/build/captures/avro/file-system/ingest-s3-capture-saver';
import { LiveTrafficIngestedWithLocalCli } from '@useoptic/analytics';
import { lockFilePath } from '../../shared/paths';
import { Config } from '../../config';
import { cleanupAndExit, makeUiBaseUrl } from '@useoptic/cli-shared';
import { getPathsRelativeToConfig, readApiConfig } from '@useoptic/cli-config';
import { Client } from '@useoptic/cli-client';
import { trackUserEvent } from '../../shared/analytics';
import * as opticEngine from '@useoptic/optic-engine-wasm';
import openBrowser from 'react-dev-utils/openBrowser';
import { linkToCapture } from '../../shared/ui-links';
import { LocalCliSpectacle } from '@useoptic/spectacle-shared';
export default class IngestS3 extends Command {
static description = 'Ingest from S3';
static hidden: boolean = true;
static flags = {
bucketName: flags.string({ required: true, char: 'b' }),
region: flags.string({ char: 'r' }),
captureId: flags.string({ char: 'c', required: true }),
pathPrefix: flags.string({ required: false }),
endpointOverride: flags.string({ required: false }),
};
async run() {
try {
const {
flags: { bucketName, region, captureId, pathPrefix, endpointOverride },
} = this.parse(IngestS3);
let interactionCount = await ingestS3({
bucketName,
region,
captureId,
pathPrefix,
endpointOverride,
});
const daemonState = await ensureDaemonStarted(
lockFilePath,
Config.apiBaseUrl
);
const apiBaseUrl = `http://localhost:${daemonState.port}/api`;
const paths = await getPathsRelativeToConfig();
const cliClient = new Client(apiBaseUrl);
const cliSession = await cliClient.findSession(paths.cwd, null, null);
const uiBaseUrl = makeUiBaseUrl(daemonState);
openBrowser(linkToCapture(uiBaseUrl, cliSession.session.id, captureId));
const apiCfg = await readApiConfig(paths.configPath);
const spectacle = new LocalCliSpectacle(
`${apiBaseUrl}/specs/${cliSession.session.id}`,
opticEngine
);
const requestQuery = await spectacle.query<any>({
query: `{
metadata {
id
}
}`,
variables: {},
});
const specId = requestQuery?.data?.metadata?.id ?? 'anon-spec-id';
/*
captureId: Joi.string().required(),
interactionCount: Joi.number().required()
*/
await trackUserEvent({
apiName: apiCfg.name,
specId,
event: LiveTrafficIngestedWithLocalCli({
captureId,
interactionCount,
}),
});
cleanupAndExit();
} catch (e) {
this.error(e);
}
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ShapeRenderer/index.ts
|
export * from './ShapeRenderer';
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/ReviewEndpointDiffPage/index.ts
|
export * from './ReviewEndpointDiffPageContainer';
|
tony-aq/optic
|
workspaces/graph-lib/src/endpoints-graph/index.ts
|
import { GraphCommandHandler, mapAppend, NodeListWrapper } from '../shared';
export type NodeId = string;
export enum NodeType {
Path = 'Path',
Request = 'Request',
QueryParameters = 'QueryParameters',
Response = 'Response',
Endpoint = 'Endpoint',
Body = 'Body',
BatchCommit = 'BatchCommit',
}
export type Node =
| PathNode
| RequestNode
| ResponseNode
| EndpointNode
| BodyNode
| BatchCommitNode
| QueryParametersNode;
export type PathNode = {
id: NodeId;
type: NodeType.Path;
data: {
absolutePathPattern: string;
pathId: string;
name: string;
isParameterized: boolean;
isRemoved: boolean;
};
};
export type RequestNode = {
id: NodeId;
type: NodeType.Request;
data: {
requestId: string;
isRemoved: boolean;
};
};
export type ResponseNode = {
id: NodeId;
type: NodeType.Response;
data: {
responseId: string;
httpStatusCode: number;
isRemoved: boolean;
};
};
export type EndpointNode = {
id: NodeId;
type: NodeType.Endpoint;
data: {
pathId: string;
httpMethod: string;
id: string;
isRemoved: boolean;
};
};
export type BodyNode = {
id: NodeId;
type: NodeType.Body;
data: {
httpContentType: string;
rootShapeId: string;
isRemoved: boolean;
};
};
export type BatchCommitNode = {
id: NodeId;
type: NodeType.BatchCommit;
data: BatchCommitData;
};
export type QueryParametersNode = {
id: NodeId;
type: NodeType.QueryParameters;
data: {
queryParametersId: string;
rootShapeId: string | null;
httpMethod: string;
isRemoved: boolean;
};
};
export type BatchCommitData = {
createdAt: string;
batchId: string;
commitMessage: string;
};
export type NodeWrapper =
| BodyNodeWrapper
| EndpointNodeWrapper
| RequestNodeWrapper
| ResponseNodeWrapper
| QueryParametersNodeWrapper
| PathNodeWrapper
| BatchCommitNodeWrapper;
// Is there a better way of infering / mapping a type to another type?
type NodeTypeToNodeWrapper<T extends NodeType> = T extends NodeType.BatchCommit
? BatchCommitNodeWrapper
: T extends NodeType.Body
? BodyNodeWrapper
: T extends NodeType.Path
? PathNodeWrapper
: T extends NodeType.Request
? RequestNodeWrapper
: T extends NodeType.QueryParameters
? QueryParametersNodeWrapper
: T extends NodeType.Response
? ResponseNodeWrapper
: T extends NodeType.Endpoint
? EndpointNodeWrapper
: NodeWrapper;
export enum EdgeType {
IsChildOf = 'IsChildOf',
CreatedIn = 'CreatedIn',
UpdatedIn = 'UpdatedIn',
RemovedIn = 'RemovedIn',
}
export type Edge =
| {
type: EdgeType.IsChildOf;
}
| {
type: EdgeType.UpdatedIn;
}
| {
type: EdgeType.CreatedIn;
}
| {
type: EdgeType.UpdatedIn;
};
////////////////////////////////////////////////////////////////////////////////
// A batch commit node can never be removed
const isNodeRemoved = (node: Node): boolean =>
node.type !== NodeType.BatchCommit && node.data.isRemoved;
////////////////////////////////////////////////////////////////////////////////
export class GraphIndexer implements GraphCommandHandler<Node, NodeId, Edge> {
readonly nodesById: Map<NodeId, Node>;
readonly nodesByType: Map<NodeType, Node[]>;
readonly outboundNeighbors: Map<NodeId, Map<NodeType, Node[]>>;
readonly inboundNeighbors: Map<NodeId, Map<NodeType, Node[]>>;
readonly outboundNeighborsByEdgeType: Map<NodeId, Map<EdgeType, Node[]>>;
readonly inboundNeighborsByEdgeType: Map<NodeId, Map<EdgeType, Node[]>>;
constructor() {
this.nodesByType = new Map();
this.nodesById = new Map();
this.outboundNeighbors = new Map();
this.inboundNeighbors = new Map();
this.outboundNeighborsByEdgeType = new Map();
this.inboundNeighborsByEdgeType = new Map();
}
addNode(node: Node) {
if (this.nodesById.has(node.id)) {
throw new Error(
`could not add a node with an id that already exists in the graph`
);
}
this.unsafeAddNode(node);
}
addEdge(edge: Edge, sourceNodeId: NodeId, targetNodeId: NodeId) {
const sourceNode = this.nodesById.get(sourceNodeId);
if (!sourceNode) {
throw new Error(`expected ${sourceNodeId} to exist`);
}
const targetNode = this.nodesById.get(targetNodeId);
if (!targetNode) {
throw new Error(`expected ${targetNodeId} to exist`);
}
const outboundNeighbors =
this.outboundNeighbors.get(sourceNodeId) || new Map();
mapAppend(outboundNeighbors, targetNode.type, targetNode);
this.outboundNeighbors.set(sourceNodeId, outboundNeighbors);
const outboundNeighborsByEdgeType =
this.outboundNeighborsByEdgeType.get(sourceNodeId) || new Map();
mapAppend(outboundNeighborsByEdgeType, edge.type, targetNode);
this.outboundNeighborsByEdgeType.set(
sourceNodeId,
outboundNeighborsByEdgeType
);
const inboundNeighbors =
this.inboundNeighbors.get(targetNodeId) || new Map();
mapAppend(inboundNeighbors, sourceNode.type, sourceNode);
this.inboundNeighbors.set(targetNodeId, inboundNeighbors);
const inboundNeighborsByEdgeType =
this.inboundNeighborsByEdgeType.get(targetNodeId) || new Map();
mapAppend(inboundNeighborsByEdgeType, edge.type, sourceNode);
this.inboundNeighborsByEdgeType.set(
targetNodeId,
inboundNeighborsByEdgeType
);
}
unsafeAddNode(node: Node) {
this.nodesById.set(node.id, node);
mapAppend(this.nodesByType, node.type, node);
}
}
////////////////////////////////////////////////////////////////////////////////
export class BodyNodeWrapper {
constructor(public result: BodyNode, private queries: GraphQueries) {}
get value() {
return this.result.data;
}
response(): ResponseNodeWrapper | null {
const neighbors = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Response
);
if (neighbors.results.length === 0) {
return null;
}
return neighbors.results[0];
}
request(): RequestNodeWrapper | null {
const neighbors = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Request
);
if (neighbors.results.length === 0) {
return null;
}
return neighbors.results[0];
}
}
export class EndpointNodeWrapper {
constructor(public result: EndpointNode, private queries: GraphQueries) {}
get value() {
return this.result.data;
}
path() {
const neighbors = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Path
);
if (neighbors.results.length === 0) {
throw new Error(`expected endpoint to have a parent Path`);
}
return neighbors.results[0];
}
query(): QueryParametersNodeWrapper | null {
const queryParameters = this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.QueryParameters
);
return queryParameters.results.length > 0
? queryParameters.results[0]
: null;
}
requests() {
return this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Request
);
}
responses() {
return this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Response
);
}
}
export class RequestNodeWrapper {
constructor(public result: RequestNode, private queries: GraphQueries) {}
get value() {
return this.result.data;
}
// A request node can be orphaned
endpoint(): EndpointNodeWrapper | null {
const endpoints = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Endpoint
);
return endpoints.results.length > 0 ? endpoints.results[0] : null;
}
body(): BodyNodeWrapper | null {
const bodies = this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Body
);
return bodies.results.length >= 1 ? bodies.results[0] : null;
}
}
export class ResponseNodeWrapper {
constructor(public result: ResponseNode, private queries: GraphQueries) {}
get value() {
return this.result.data;
}
// A response node can be orphaned
endpoint(): EndpointNodeWrapper | null {
const endpoints = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Endpoint
);
return endpoints.results.length > 0 ? endpoints.results[0] : null;
}
bodies() {
return this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Body
);
}
}
export class QueryParametersNodeWrapper {
constructor(
public result: QueryParametersNode,
private queries: GraphQueries
) {}
get value() {
return this.result.data;
}
// A response node can be orphaned
endpoint(): EndpointNodeWrapper | null {
const endpoints = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Endpoint
);
return endpoints.results.length > 0 ? endpoints.results[0] : null;
}
}
export class PathNodeWrapper {
constructor(public result: PathNode, private queries: GraphQueries) {}
get value() {
return this.result.data;
}
parentPath() {
const parentPaths = this.queries.listOutgoingNeighborsByType(
this.result.id,
NodeType.Path
);
if (parentPaths.results.length === 0) {
return null;
}
const [parentPath] = parentPaths.results;
return parentPath;
}
endpoints() {
return this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Endpoint
);
}
components(): PathNodeWrapper[] {
let pathNode = this as PathNodeWrapper;
let parentPath = pathNode.parentPath();
const components = [pathNode];
while (parentPath !== null) {
components.push(parentPath);
pathNode = parentPath;
parentPath = pathNode.parentPath();
}
return components.reverse();
}
get absolutePathPatternWithParameterNames(): string {
let path = '';
const components = this.components();
if (components.length === 1 && components[0].value.pathId === 'root') {
return '/';
}
for (const component of components) {
if (component.value.pathId === 'root') continue;
if (component.value.isParameterized) {
path = `${path}/{${component.value.name}}`;
} else {
path = `${path}/${component.value.name}`;
}
}
return path;
}
}
export class BatchCommitNodeWrapper {
constructor(public result: BatchCommitNode, private queries: GraphQueries) {}
get value() {
return this.result.data;
}
requests() {
return this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Request
);
}
responses() {
return this.queries.listIncomingNeighborsByType(
this.result.id,
NodeType.Response
);
}
createdInEdgeNodes() {
return this.queries.listIncomingNeighborsByEdgeType(
this.result.id,
EdgeType.CreatedIn
);
}
updatedInEdgeNodes() {
return this.queries.listIncomingNeighborsByEdgeType(
this.result.id,
EdgeType.UpdatedIn
);
}
removedInEdgeNodes() {
return this.queries.listIncomingNeighborsByEdgeType(
this.result.id,
EdgeType.RemovedIn
);
}
}
////////////////////////////////////////////////////////////////////////////////
export class GraphQueries {
constructor(private index: GraphIndexer) {}
findNodeById(id: NodeId): NodeWrapper | null {
const node = this.index.nodesById.get(id);
if (!node) {
return null;
}
return this.wrap(node);
}
listNodesByType<T extends NodeType>(
type: T,
{
includeRemoved = true,
}: {
includeRemoved?: boolean;
} = {}
): NodeListWrapper<NodeTypeToNodeWrapper<T>> {
const nodesByType = this.index.nodesByType.get(type) || [];
const filteredNodesByType = includeRemoved
? nodesByType
: nodesByType.filter((node) => !isNodeRemoved(node));
return this.wrapList(type, filteredNodesByType) as NodeListWrapper<
NodeTypeToNodeWrapper<T>
>;
}
//@TODO add singular find* variant
listIncomingNeighborsByType<T extends NodeType>(
id: NodeId,
incomingNeighborType: T,
{
includeRemoved = true,
}: {
includeRemoved?: boolean;
} = {}
): NodeListWrapper<NodeTypeToNodeWrapper<T>> {
const neighbors = this.index.inboundNeighbors.get(id);
if (!neighbors) {
return this.wrapList(incomingNeighborType, []) as NodeListWrapper<
NodeTypeToNodeWrapper<T>
>;
}
const neighborsOfType = neighbors.get(incomingNeighborType) || [];
const filteredNeighborsOfType = includeRemoved
? neighborsOfType
: neighborsOfType.filter((node) => !isNodeRemoved(node));
return this.wrapList(
incomingNeighborType,
filteredNeighborsOfType
) as NodeListWrapper<NodeTypeToNodeWrapper<T>>;
}
//@TODO add singular find* variant
listOutgoingNeighborsByType<T extends NodeType>(
id: NodeId,
outgoingNeighborType: T,
{
includeRemoved = true,
}: {
includeRemoved?: boolean;
} = {}
): NodeListWrapper<NodeTypeToNodeWrapper<T>> {
const neighbors = this.index.outboundNeighbors.get(id);
if (!neighbors) {
return this.wrapList(outgoingNeighborType, []) as NodeListWrapper<
NodeTypeToNodeWrapper<T>
>;
}
const neighborsOfType = neighbors.get(outgoingNeighborType) || [];
const filteredNeighborsOfType = includeRemoved
? neighborsOfType
: neighborsOfType.filter((node) => !isNodeRemoved(node));
return this.wrapList(
outgoingNeighborType,
filteredNeighborsOfType
) as NodeListWrapper<NodeTypeToNodeWrapper<T>>;
}
listIncomingNeighborsByEdgeType(
id: NodeId,
edgeType: EdgeType
): NodeListWrapper<NodeWrapper> {
const neighbors = this.index.inboundNeighborsByEdgeType.get(id);
if (!neighbors) {
return this.wrapList(null, []);
}
const neighborsOfType = neighbors.get(edgeType);
return this.wrapList(null, neighborsOfType || []);
}
listOutgoingNeighborsByEdgeType(
id: NodeId,
edgeType: EdgeType
): NodeListWrapper<NodeWrapper> {
const neighbors = this.index.outboundNeighborsByEdgeType.get(id);
if (!neighbors) {
return this.wrapList(null, []);
}
const neighborsOfType = neighbors.get(edgeType);
return this.wrapList(null, neighborsOfType || []);
}
*descendantsIterator(
nodeId: NodeId,
seenSet: Set<NodeId> = new Set(),
{
includeRemoved = true,
}: {
includeRemoved?: boolean;
} = {}
): Generator<Node> {
const inboundNeighbors = this.index.inboundNeighbors.get(nodeId);
if (!inboundNeighbors) {
return;
}
if (seenSet.has(nodeId)) {
return;
}
seenSet.add(nodeId);
for (const neighborsByNodeType of inboundNeighbors.values()) {
for (const neighborNode of neighborsByNodeType) {
if (includeRemoved || !isNodeRemoved(neighborNode)) {
yield neighborNode;
yield* this.descendantsIterator(neighborNode.id, seenSet);
}
}
}
}
//@TODO wrap() and wrapList() should be injected?
// TODO figure out how to make this generic
wrap(node: Node): NodeWrapper {
if (node.type === NodeType.Request) {
return new RequestNodeWrapper(node, this);
} else if (node.type === NodeType.Response) {
return new ResponseNodeWrapper(node, this);
} else if (node.type === NodeType.Path) {
return new PathNodeWrapper(node, this);
} else if (node.type === NodeType.Body) {
return new BodyNodeWrapper(node, this);
} else if (node.type === NodeType.QueryParameters) {
return new QueryParametersNodeWrapper(node, this);
} else if (node.type === NodeType.BatchCommit) {
return new BatchCommitNodeWrapper(node, this);
} else if (node.type === NodeType.Endpoint) {
return new EndpointNodeWrapper(node, this);
}
throw new Error(`unexpected node.type`);
}
//@TODO move away from null here
// TODO figure out how to make this generic
wrapList(type: NodeType | null, nodes: Node[]): NodeListWrapper<NodeWrapper> {
//@TODO add list helpers (map, etc.)
return {
results: nodes.map((node) => this.wrap(node)),
};
}
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/paths/index.ts
|
<reponame>tony-aq/optic<gh_stars>100-1000
export * from './slice';
|
tony-aq/optic
|
workspaces/spectacle-shared/src/index.ts
|
export * from './local-cli/client';
|
tony-aq/optic
|
workspaces/cli-shared/src/ingest/ingest-traffic-service.ts
|
<filename>workspaces/cli-shared/src/ingest/ingest-traffic-service.ts
import { developerDebugLogger, ICaptureSaver } from '../index';
import express from 'express';
import bodyParser from 'body-parser';
import fs from 'fs-extra';
import path from 'path';
import getPort from 'get-port';
import http from 'http';
import { ecsToHttpInteraction } from './ecs-to-sample';
import { HttpInteraction } from '@useoptic/optic-domain/build/streams/http-interactions';
export class IngestTrafficService {
private collectorService: express.Application;
private server: http.Server | undefined;
constructor(
private captureSaver: ICaptureSaver,
onSample: (i: HttpInteraction) => void = (i) => {}
) {
this.collectorService = express();
this.collectorService.use(bodyParser.json({ limit: '20mb' }));
//https://www.elastic.co/guide/en/ecs/current/index.html
this.collectorService.post('/ecs', this.handleEcs);
}
async start(): Promise<string> {
const servicePort: number = await getPort({
port: getPort.makeRange(3700, 3900),
});
this.server = await new Promise<http.Server>((resolve) => {
const server: http.Server = this.collectorService.listen(servicePort);
server.on('listening', () => resolve(server));
});
return `http://localhost:${servicePort}/`;
}
async stop() {
if (this.server) {
this.server.close();
this.server = undefined;
}
}
//handlers
handleEcs = async (req: express.Request, res: express.Response) => {
const samples = req.body;
samples.forEach((sample: any) => {
developerDebugLogger('saw sample', sample);
try {
this.captureSaver.save(ecsToHttpInteraction(sample));
} catch (e) {
developerDebugLogger(
'could not transform ecs sample -> interaction format',
e
);
}
});
res.sendStatus(201);
};
}
|
tony-aq/optic
|
workspaces/analytics/src/uiEvents.ts
|
<reponame>tony-aq/optic<gh_stars>100-1000
import { TrackingEventBase } from './interfaces/TrackingEventBase';
type AnalyticsDispatcher = (event: TrackingEventBase<any>) => void;
export class OpticUIEvents {
constructor(private dispatch: AnalyticsDispatcher) {}
// in-use
// documentation page
documentationPageLoaded() {
this.dispatch({
type: 'documentation_page_loaded',
data: {},
});
}
documentationListPageLoaded() {
this.dispatch({
type: 'documentation_list_page_loaded',
data: {},
});
}
userSavedDocChanges(
deletedEndpointCount: number,
contributionChangesCount: number,
specId: string
) {
this.dispatch({
type: 'user_saved_documentation_changes',
data: { deletedEndpointCount, contributionChangesCount, specId },
});
}
userLoggedIn(backendUserId: string) {
this.dispatch({
type: 'user_logged_in',
data: { backendUserId },
});
}
userStartedSharing() {
this.dispatch({
type: 'user_started_sharing',
data: {},
});
}
userPickedShareTarget(shareWith: string) {
this.dispatch({
type: 'user_picked_share_target',
data: { with: shareWith },
});
}
userShared(shareWith: string, publicSpecId: string) {
this.dispatch({
type: 'user_saved_documentation_changes',
data: { with: shareWith, publicSpecId },
});
}
userDeletedEndpoint() {
this.dispatch({
type: 'user_deleted_endpoint',
data: {},
});
}
// diff page
userResetDiff(currentApproved: number, totalDiffs: number) {
this.dispatch({
type: 'user_reset_diff',
data: { currentApproved, totalDiffs },
});
}
reviewPageLoaded(
diffs: number,
undocumentedUrls: number,
diffEngineDurationMilliseconds: number,
endpointsInSpec: number
) {
this.dispatch({
type: 'review_page_loaded',
data: {
undocumentedUrls,
diffEngineDurationMilliseconds,
endpointsInSpec,
},
});
}
userApprovedAll(shapeDiffs: number, newBodyDiffs: number) {
this.dispatch({
type: 'user_approved_all',
data: { shapeDiffs, newBodyDiffs },
});
}
userDocumentedEndpoint(isBulkMode: boolean) {
this.dispatch({
type: 'user_documented_endpoint',
data: { isBulkMode },
});
}
userDiscardedEndpoint() {
this.dispatch({
type: 'user_discarded_endpoint',
data: {},
});
}
userChoseACaptureMethod(captureSource: string) {
this.dispatch({
type: 'user_chose_capture_method',
data: { captureSource },
});
}
userSavedChanges(
undocumentedUrls: number,
endpointsChangedCount: number,
specId: string
) {
this.dispatch({
type: 'user_saved_changes',
data: {
undocumentedUrls,
endpointsChangedCount,
specId,
},
});
}
// history page
historyPageLoaded() {
this.dispatch({
type: 'history_page_loaded',
data: {},
});
}
resetToCommit(numberOfCommitsReset: number) {
this.dispatch({
type: 'reset_to_commit',
data: {
numberOfCommitsReset,
},
});
}
// Temporary
// 2021/07/13- can remove 2021/10/13
queryParameterDocumented(numberOfQueryParameterBodies: number) {
this.dispatch({
type: 'query_parameter_documented',
data: {
numberOfQueryParameterBodies,
},
});
}
// proposed
// deprecated
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ShapeRenderer/ShapeRowBase.tsx
|
<reponame>tony-aq/optic
import * as React from 'react';
import { useCallback } from 'react';
import { makeStyles } from '@material-ui/core';
import { JsonType } from '@useoptic/optic-domain';
import { IndentSpaces, useSharedStyles } from './SharedStyles';
import { IFieldRenderer, IShapeRenderer } from '<src>/types';
import { ShapePrimitiveRender, UnknownPrimitiveRender } from './ShapePrimitive';
import { useDepth } from './DepthContext';
import classNames from 'classnames';
import { useShapeRenderContext } from './ShapeRenderContext';
import { OneOfTabs, OneOfTabsProps } from './OneOfTabs';
import { ChangeType } from '<src>/types';
type ShapeRowBaseProps = {
children: any;
depth: number;
style?: any;
changes?: ChangeType | null;
focused?: boolean;
clickable?: boolean;
onClick?: () => void;
} & React.HtmlHTMLAttributes<HTMLDivElement>;
export const ShapeRowBase = ({
children,
depth = 0,
style,
changes,
focused,
clickable,
onClick,
...props
}: ShapeRowBaseProps) => {
const classes = useStyles();
const sharedClasses = useSharedStyles();
const onClickWrap = useCallback(
(e: React.MouseEvent) => {
if (!clickable) return;
e.preventDefault();
if (onClick) onClick();
},
[clickable, onClick]
);
return (
<div
style={style}
className={classNames(classes.rowWrap, {
[classes.allowHover]: false,
[classes.isFocused]: focused,
[classes.isClickable]: clickable,
})}
onClick={onClickWrap}
>
<div
{...props}
className={classNames(
classes.row,
{ [sharedClasses.added]: changes === 'added' },
{ [sharedClasses.changed]: changes === 'updated' },
{ [sharedClasses.removed]: changes === 'removed' }
)}
style={{ paddingLeft: depth * IndentSpaces + 4 }}
>
{children}
</div>
</div>
);
};
export const RenderField = ({
name,
shapeChoices,
required,
shapeId,
changes,
fieldId,
}: IFieldRenderer) => {
const sharedClasses = useSharedStyles();
const { depth } = useDepth();
const {
getChoice,
selectedFieldId,
fieldsAreSelectable,
selectField,
} = useShapeRenderContext();
const onClickRow = useCallback(() => {
selectField(fieldId);
}, [selectField, fieldId]);
if (shapeChoices.length === 1) {
return (
<>
<ShapeRowBase
depth={depth}
changes={changes}
clickable={fieldsAreSelectable}
focused={!selectedFieldId || fieldId === selectedFieldId}
data-fieldid={fieldId}
onClick={onClickRow}
>
<span className={sharedClasses.shapeFont}>"{name}"</span>
<span className={sharedClasses.symbolFont}>: </span>
<RenderFieldLeadingValue shapeRenderers={shapeChoices} />
{!required && (
<span className={sharedClasses.symbolFont}> (optional) </span>
)}
</ShapeRowBase>
<RenderFieldRowValues shapeRenderers={shapeChoices} />
</>
);
} else if (shapeChoices.length === 0) {
return (
<ShapeRowBase
depth={depth}
changes={changes}
clickable={fieldsAreSelectable}
focused={!selectedFieldId || fieldId === selectedFieldId}
data-fieldid={fieldId}
onClick={onClickRow}
>
<span className={sharedClasses.shapeFont}>"{name}"</span>
<span className={sharedClasses.symbolFont}>: </span>
<UnknownPrimitiveRender />
</ShapeRowBase>
);
} else {
const tabprops: OneOfTabsProps = {
shapeId,
choices: shapeChoices.map((i) => ({
label: i.jsonType,
id: i.shapeId,
})),
};
const current = getChoice(tabprops);
const toRenderShape =
shapeChoices.find((i) => i.shapeId === current) || shapeChoices[0];
//one of
return (
<>
<ShapeRowBase
depth={depth}
changes={changes}
clickable={fieldsAreSelectable}
focused={!selectedFieldId || fieldId === selectedFieldId}
data-fieldid={fieldId}
onClick={onClickRow}
>
<span className={sharedClasses.shapeFont}>"{name}"</span>
<span className={sharedClasses.symbolFont}>: </span>
{toRenderShape && (
<RenderFieldLeadingValue shapeRenderers={[toRenderShape]} />
)}
{!required && (
<span className={sharedClasses.symbolFont}> (optional) </span>
)}
<div style={{ flex: 1 }} />
<OneOfTabs {...tabprops} />
</ShapeRowBase>
{toRenderShape && (
<RenderFieldRowValues shapeRenderers={[toRenderShape]} />
)}
</>
);
}
};
export const RenderRootShape = ({
shape,
right,
}: {
shape: IShapeRenderer;
right?: React.ReactElement;
}) => {
const { depth } = useDepth();
const { selectedFieldId } = useShapeRenderContext();
return (
<>
<ShapeRowBase depth={depth} focused={!selectedFieldId}>
<RenderFieldLeadingValue shapeRenderers={[shape]} />
{right ? (
<>
<div style={{ flex: 1 }} />
{right}
</>
) : null}
</ShapeRowBase>
<RenderFieldRowValues shapeRenderers={[shape]} />
</>
);
};
type RenderFieldValueProps = {
shapeRenderers: IShapeRenderer[];
};
export const RenderFieldLeadingValue = ({
shapeRenderers,
}: RenderFieldValueProps) => {
const sharedClasses = useSharedStyles();
const shape = shapeRenderers[0];
if (!shape) {
return null;
}
if (shape.jsonType === JsonType.OBJECT) {
return (
<>
<span className={sharedClasses.symbolFont}>{'{'}</span>
</>
);
}
if (shape.jsonType === JsonType.ARRAY && shape.asArray) {
return (
<>
<span className={sharedClasses.symbolFont}>{'['}</span>
</>
);
}
return (
<>
<ShapePrimitiveRender {...shape} />
</>
);
};
export const RenderFieldRowValues = ({
shapeRenderers,
}: RenderFieldValueProps) => {
const sharedClasses = useSharedStyles();
const { Indent, depth } = useDepth();
const { selectedFieldId } = useShapeRenderContext();
if (shapeRenderers.length === 1) {
const shape = shapeRenderers[0];
if (shape.asObject) {
return (
<>
{shape.asObject.fields.map((field) => (
<Indent key={field.fieldId}>
<RenderField {...field} />
</Indent>
))}
<ShapeRowBase depth={depth} focused={!selectedFieldId}>
<span className={sharedClasses.symbolFont}>{'}'}</span>
</ShapeRowBase>
</>
);
}
if (shape.asArray) {
if (shape.asArray.shapeChoices.length === 0) {
return (
<>
<ShapePrimitiveRender {...shape} />
<ShapeRowBase depth={depth} focused={!selectedFieldId}>
<span className={sharedClasses.symbolFont}>{']'}</span>
</ShapeRowBase>
</>
);
}
const inner =
shape.asArray.shapeChoices.length > 1 ? (
<OneOfRender
shapeId={shape.asArray.shapeId}
shapes={shape.asArray.shapeChoices}
/>
) : shape.asArray.shapeChoices.length === 1 ? (
<RenderRootShape shape={shape.asArray.shapeChoices[0]} />
) : null;
return (
<>
<Indent>{inner}</Indent>
<ShapeRowBase depth={depth} focused={!selectedFieldId}>
<span className={sharedClasses.symbolFont}>{']'}</span>
</ShapeRowBase>
</>
);
}
return <></>;
} else {
return null;
}
};
export function OneOfRender({
shapes,
shapeId,
}: {
shapes: IShapeRenderer[];
shapeId: string;
}) {
const { getChoice } = useShapeRenderContext();
if (shapes.length === 1) {
throw new Error('This is not a one of');
}
const choices = shapes.map((i) => ({
label: i.jsonType.toString().toLowerCase(),
id: i.shapeId,
}));
const tabProps = {
choices,
shapeId,
};
const chosenShapeToRender = choices.find((i) => i.id === getChoice(tabProps));
if (!chosenShapeToRender) {
return null;
}
const shape = shapes.find((i) => chosenShapeToRender.id === i.shapeId);
if (!shape) {
throw new Error(`expected to find the chosen shape`);
}
return <RenderRootShape right={<OneOfTabs {...tabProps} />} shape={shape} />;
}
const useStyles = makeStyles((theme) => ({
rowWrap: {
display: 'flex',
},
allowHover: {
'&:hover $row': {
backgroundColor: '#e4ebf1',
},
},
row: {
flex: 1,
display: 'flex',
alignItems: 'flex-start',
minHeight: 17,
'$rowWrap:not($isFocused) &': {
opacity: 0.3,
},
'$isClickable &:hover': {
backgroundColor: '#e4ebf1',
cursor: 'pointer',
},
'$isClickable:not($isFocused) &:hover': {
opacity: 0.6,
},
},
isClickable: {},
isFocused: {},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/hooks/useInteraction.tsx
|
<reponame>tony-aq/optic<filename>workspaces/ui-v2/src/hooks/useInteraction.tsx<gh_stars>100-1000
import { useContext, useEffect, useState } from 'react';
import * as Sentry from '@sentry/react';
import { IHttpInteraction } from '@useoptic/optic-domain';
import { AsyncStatus } from '<src>/types';
import { CapturesServiceContext } from './useCapturesHook';
export function useInteraction(
captureId: string,
pointer: string
): AsyncStatus<IHttpInteraction> {
const capturesService = useContext(CapturesServiceContext);
const [result, setResult] = useState<AsyncStatus<IHttpInteraction>>({
loading: true,
});
useEffect(() => {
if (capturesService) {
capturesService
.loadInteraction(captureId, pointer)
.then((interaction: IHttpInteraction) => {
setResult({ loading: false, data: interaction });
})
.catch((e) => {
console.error(
`Could not find interaction ${pointer} for capture ${captureId}`
);
Sentry.captureException(e);
setResult({ loading: false, error: e });
});
} else {
setResult({ loading: false, error: new Error() });
}
}, [pointer, captureId, capturesService]);
return result;
}
|
tony-aq/optic
|
workspaces/cli-shared/src/captures/avro/index.ts
|
<filename>workspaces/cli-shared/src/captures/avro/index.ts
import avro from 'avsc';
export const schema: any = {
type: 'record',
name: 'InteractionBatch',
namespace: 'com.useoptic.types.capture',
fields: [
{
name: 'groupingIdentifiers',
type: {
type: 'record',
name: 'GroupingIdentifiers',
fields: [
{ name: 'agentGroupId', type: 'string' },
{ name: 'captureId', type: 'string' },
{ name: 'agentId', type: 'string' },
{ name: 'batchId', type: 'string' },
],
},
},
{
name: 'batchItems',
type: {
type: 'array',
items: {
type: 'record',
name: 'HttpInteraction',
fields: [
{ name: 'uuid', type: 'string' },
{
name: 'request',
type: {
type: 'record',
name: 'Request',
fields: [
{ name: 'host', type: 'string' },
{ name: 'method', type: 'string' },
{ name: 'path', type: 'string' },
{
name: 'query',
type: {
type: 'record',
name: 'ArbitraryData',
fields: [
{
name: 'shapeHashV1Base64',
type: ['null', 'string'],
default: null,
},
{
name: 'asJsonString',
type: ['null', 'string'],
default: null,
},
{
name: 'asText',
type: ['null', 'string'],
default: null,
},
],
},
},
{ name: 'headers', type: 'ArbitraryData' },
{
name: 'body',
type: {
type: 'record',
name: 'Body',
fields: [
{ name: 'contentType', type: ['null', 'string'] },
{ name: 'value', type: 'ArbitraryData' },
],
},
},
],
},
},
{
name: 'response',
type: {
type: 'record',
name: 'Response',
fields: [
{ name: 'statusCode', type: 'int' },
{ name: 'headers', type: 'ArbitraryData' },
{ name: 'body', type: 'Body' },
],
},
},
{
name: 'tags',
type: {
type: 'array',
items: {
type: 'record',
name: 'HttpInteractionTag',
fields: [
{ name: 'name', type: 'string' },
{ name: 'value', type: 'string' },
],
},
},
},
],
},
},
},
],
};
export const serdes = avro.Type.forSchema(schema);
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelog/ChangelogPages.tsx
|
<gh_stars>100-1000
import React from 'react';
import { Switch, Redirect, Route, useParams } from 'react-router-dom';
import {
useChangelogPages,
useChangelogEndpointPageLink,
} from '<src>/components/navigation/Routes';
import { useFetchEndpoints } from '<src>/hooks/useFetchEndpoints';
import { ChangelogListPage } from './ChangelogListPage';
import { ChangelogEndpointRootPage } from './ChangelogEndpointRootPage';
export function ChangelogPages() {
const changelogPages = useChangelogPages();
const changelogEndpointPageLink = useChangelogEndpointPageLink();
const { batchId } = useParams<{
pathId: string;
method: string;
batchId: string;
}>();
useFetchEndpoints(batchId);
return (
<Switch>
<Route
exact
path={changelogEndpointPageLink.path}
component={ChangelogEndpointRootPage}
/>
<Route exact path={changelogPages.path} component={ChangelogListPage} />
<Redirect to={changelogPages.path} />
</Switch>
);
}
|
tony-aq/optic
|
workspaces/spectacle/src/openapi/json-schema.ts
|
<reponame>tony-aq/optic<gh_stars>100-1000
export async function jsonSchemaFromShapeId(
spectacle: any,
shapeId: string
): Promise<JsonSchema> {
const shape = await queryForShape(spectacle, shapeId);
// We ignore Undefined here because we check in when dealing with Object
const shapeChoices = shape.data.shapeChoices.filter(
(shapeChoice: any) => shapeChoice.jsonType !== 'Undefined'
);
const schemas: JsonSchemaType[] = await Promise.all(
shapeChoices.map(async (shapeChoice: any) => {
return await jsonSchemaFromShapeChoice(spectacle, shapeChoice);
})
);
// jsonSchemaFromShapeChoice can return `{ type: 'null' }`, but OpenAPI 3.0.3 cannot handle this type
// Instead, it requires using a `nullable` property.
let isNullable = false;
// This is how we find out if the schemas are nullable while removing any `{ type: 'null' }`
// from the final results.
const openApiSchemas: JsonSchemaType[] = schemas.filter((schema) => {
if (schema.type === 'null') {
isNullable = true;
return false;
}
return true;
});
// This happens when there is only a null type
// We are taking liberties here to set the type as string, which may not be correct.
if (isNullable && openApiSchemas.length === 0) {
return { nullable: true };
}
// TODO: investigate why this scenario happens
// This can happen if there are no shapeChoices
if (openApiSchemas.length === 0) {
return {};
}
// This means it's nullable with additional types to for setting `nullable: true`.
if (isNullable) {
for (const schema of openApiSchemas) {
if (schema.type !== 'null') schema.nullable = true;
}
}
if (openApiSchemas.length === 1) return openApiSchemas[0];
// In some cases, it might be nicer to do { type: [string, number] }, but this
// isn't supported in OpenAPI. Leaving it as oneOf for now.
return { oneOf: openApiSchemas };
}
export async function jsonSchemaFromShapeChoice(
spectacle: any,
shapeChoice: any
): Promise<JsonSchemaType> {
if (shapeChoice.jsonType === 'Object') {
const result: JsonSchemaObject = {
type: 'object',
properties: {},
required: [],
};
for (const field of shapeChoice.asObject.fields) {
result.properties[field.name] = (await jsonSchemaFromShapeId(
spectacle,
field.shapeId
)) as any;
if ('description' in field.contributions) {
result.properties[field.name].description =
field.contributions.description;
}
let isRequired = true;
// We look down into the field shape choices to see if Undefined shows up
// anywhere. If we find one, we don't mark the field as required.
const fieldShape = await queryForShape(spectacle, field.shapeId);
for (const shapeChoice of (fieldShape as any).data.shapeChoices) {
if (shapeChoice.jsonType === 'Undefined') {
isRequired = false;
break;
}
}
if (isRequired) result.required?.push(field.name);
}
if (!result.required?.length) delete result.required;
return result;
}
if (shapeChoice.jsonType === 'Array') {
const itemSchema = await jsonSchemaFromShapeId(
spectacle,
shapeChoice.asArray.shapeId
);
return {
type: 'array',
items: itemSchema,
};
}
if (shapeChoice.jsonType === 'String') {
return { type: 'string' };
}
if (shapeChoice.jsonType === 'Number') {
return { type: 'number' };
}
if (shapeChoice.jsonType === 'Boolean') {
return { type: 'boolean' };
}
if (shapeChoice.jsonType === 'Null') {
return { type: 'null' };
}
throw new TypeError(`Unknown JSON type ${shapeChoice.jsonType}`);
}
export async function queryForShape(spectacle: any, shapeId: string) {
return await spectacle.queryWrapper({
query: `query GetShape($shapeId: ID!) {
shapeChoices(shapeId: $shapeId) {
jsonType
asArray {
shapeId
}
asObject {
fields {
shapeId
name
contributions
}
}
}
}`,
variables: { shapeId },
});
}
export type JsonSchema = JsonSchemaType | JsonSchemaOneOf;
export type JsonSchemaType =
| JsonSchemaObject
| JsonSchemaArray
| JsonSchemaValue;
export type JsonSchemaObject = {
type: 'object';
description?: string;
properties: {
[property: string]: JsonSchema;
};
required?: string[];
nullable?: boolean;
};
export type JsonSchemaArray = {
type: 'array';
description?: string;
items: JsonSchema;
nullable?: boolean;
};
export type JsonSchemaValue =
| {
type?: 'string' | 'number' | 'boolean';
description?: string;
nullable?: boolean;
}
| { type: 'null'; description?: string };
export type JsonSchemaOneOf = {
oneOf: JsonSchema[];
description?: string;
};
|
tony-aq/optic
|
workspaces/spectacle/src/main.ts
|
import { makeSpectacle } from './index';
import * as OpticEngine from '@useoptic/optic-engine-wasm';
import { InMemoryOpticContextBuilder } from './in-memory';
import * as fs from 'fs';
function loadExampleSpec(name: string): any[] {
return JSON.parse(
fs
.readFileSync(`./workspaces/spectacle/examples/${name}.json`)
.toString('utf-8')
);
}
// TODO: replace examples with snapshot tests
const _events = loadExampleSpec('array-changes');
async function main() {
const opticContext = await InMemoryOpticContextBuilder.fromEvents(
OpticEngine,
_events
);
const spectacle = await makeSpectacle(opticContext);
const batchCommitResults = await spectacle.queryWrapper({
query: `{
batchCommits {
createdAt
batchId
}
}`,
variables: {},
});
// console.log(JSON.stringify(batchCommitResults, null, 2));
const endpointChangesResult = await spectacle.queryWrapper({
query: `{
endpointChanges(sinceBatchCommitId: "645a4137-d59d-4d9f-a474-d2bca67ba1cc") {
endpoints {
change {
category
}
path
method
}
}
}`,
variables: {},
});
console.log(JSON.stringify(endpointChangesResult, null, 2));
const result = await spectacle.queryWrapper({
query: `{
requests {
id
pathId
absolutePathPattern
method
bodies {
contentType
rootShapeId
}
responses {
id
statusCode
bodies {
contentType
rootShapeId
}
}
}
}`,
variables: {},
});
console.log(JSON.stringify(result, null, 2));
{
// array shape_Dw5kY43tt1
// object shape_jSAthS01Bb
const result = await spectacle.queryWrapper({
query: `{
shapeChoices(shapeId: "shape_jSAthS01Bb") {
id
jsonType
asArray {
changes(sinceBatchCommitId: "645a4137-d59d-4d9f-a474-d2bca67ba1cc") {
added
changed
}
}
asObject {
fields {
shapeId
fieldId
name
changes(sinceBatchCommitId: "645a4137-d59d-4d9f-a474-d2bca67ba1cc") {
added
changed
}
}
}
}
}`,
variables: {},
});
console.log(JSON.stringify(result, null, 2));
}
}
main();
|
tony-aq/optic
|
workspaces/ui-v2/src/utils/pathMatcher.ts
|
export type PathComponentAuthoring = {
index: number;
name: string;
originalName: string;
isParameter: boolean;
};
export function urlStringToPathComponents(
url: string
): PathComponentAuthoring[] {
const components: PathComponentAuthoring[] = url
.split('/')
.map((name, index) => {
return { index, name, originalName: name, isParameter: false };
});
const [root, ...rest] = components;
if (root.name === '') {
return rest;
}
return components;
}
export const createPathFromPathComponents = (
components: PathComponentAuthoring[]
) => {
return (
'/' +
components
.map((i) => {
return i.isParameter ? `{${i.name}}` : i.originalName;
})
.join('/')
);
};
export const pathMatcher = (
pathComponents: PathComponentAuthoring[]
): ((pathToMatch: string) => boolean) => {
return (pathToMatch: string): boolean => {
const partsToMatch = urlStringToPathComponents(pathToMatch);
if (partsToMatch.length !== pathComponents.length) {
return false;
}
return pathComponents.every(({ name, isParameter }, i) => {
return isParameter || name === partsToMatch[i].name;
});
};
};
|
tony-aq/optic
|
workspaces/ui-v2/src/constants/index.ts
|
export * from './SupportLinks';
|
tony-aq/optic
|
workspaces/ui-v2/src/utils/__tests__/pathMatcher.test.ts
|
import { pathMatcher, urlStringToPathComponents } from '../pathMatcher';
test('generates a matcher expression from a path', () => {
const matcher = pathMatcher(
urlStringToPathComponents('/api/123/hello').map((part) => {
if (part.name === '123') {
part.isParameter = true;
}
return part;
})
);
expect(matcher('/api/some_other_path/hello')).toBe(true);
expect(matcher('/api/123/hello')).toBe(true);
expect(matcher('/api/123')).toBe(false);
});
test('generates a matcher with special characters', () => {
const matcher = pathMatcher(
urlStringToPathComponents('/api/123/hel-lo[/**').map((part) => {
if (part.name === '123') {
part.isParameter = true;
}
return part;
})
);
expect(matcher('/api/some_other_path/hel-lo[/**')).toBe(true);
expect(matcher('/api/123/hel-lo[/**')).toBe(true);
expect(matcher('/api/123/hel-lo[/*')).toBe(false);
});
test('treats dashes as the same named path parameter', () => {
const matcher = pathMatcher(
urlStringToPathComponents('/api/some-other-path/feed').map((part) => {
if (part.name === 'some-other-path') {
part.isParameter = true;
}
return part;
})
);
expect(matcher('/api/someother_path/feed')).toBe(true);
expect(matcher('/api/123/feed')).toBe(true);
expect(matcher('/api/123/notfeed')).toBe(false);
});
test('handles named path parameters with multiple colons', () => {
const matcherColonStart = pathMatcher(
urlStringToPathComponents('/api/:::hello/feed').map((part) => {
if (part.name === ':::hello') {
part.isParameter = true;
}
return part;
})
);
const matcherColonMiddle = pathMatcher(
urlStringToPathComponents('/api/:hel:lo/feed').map((part) => {
if (part.name === ':hel:lo') {
part.isParameter = true;
}
return part;
})
);
for (const matcher of [matcherColonStart, matcherColonMiddle]) {
expect(matcher('/api/someother_path/feed')).toBe(true);
expect(matcher('/api/123/feed')).toBe(true);
expect(matcher('/api/123/notfeed')).toBe(false);
}
});
test('treats special characters as the same named path parameter', () => {
const matcherWithPlus = pathMatcher(
urlStringToPathComponents('/api/:+/feed').map((part) => {
if (part.name === ':+') {
part.isParameter = true;
}
return part;
})
);
const matcherWithSpecialCharactersInBetween = pathMatcher(
urlStringToPathComponents('/api/:abc+def/feed').map((part) => {
if (part.name === ':abc+def') {
part.isParameter = true;
}
return part;
})
);
for (const matcher of [
matcherWithPlus,
matcherWithSpecialCharactersInBetween,
]) {
expect(matcher('/api/someother_path/feed')).toBe(true);
expect(matcher('/api/123/feed')).toBe(true);
expect(matcher('/api/123/notfeed')).toBe(false);
}
});
|
tony-aq/optic
|
workspaces/spectacle/src/helpers.ts
|
import { shapes, endpoints } from '@useoptic/graph-lib';
import { CQRSCommand, JsonType } from '@useoptic/optic-domain';
import { IOpticEngine, IOpticEngineIdGenerationStrategy } from './types';
export function buildEndpointsGraph(spec: any, opticEngine: any) {
const serializedGraph = JSON.parse(
opticEngine.get_endpoints_projection(spec)
);
const { nodes, edges, nodeIndexToId } = serializedGraph;
const indexer = new endpoints.GraphIndexer();
function remapId(arrayIndex: number) {
const fallbackId = arrayIndex.toString();
const id = nodeIndexToId[fallbackId];
if (id !== undefined) {
return id;
}
return fallbackId;
}
nodes.forEach((node: endpoints.Node, index: number) => {
const id = remapId(index);
indexer.addNode({
...node,
id,
});
});
edges.forEach((e: [number, number, any]) => {
const [sourceIndex, targetIndex, edge] = e;
indexer.addEdge(edge, remapId(sourceIndex), remapId(targetIndex));
});
const queries = new endpoints.GraphQueries(indexer);
return queries;
}
export function buildShapesGraph(spec: any, opticEngine: any) {
const serializedGraph = JSON.parse(opticEngine.get_shapes_projection(spec));
const { nodes, edges, nodeIndexToId } = serializedGraph;
// console.log('nodes', nodes);
const indexer = new shapes.GraphIndexer();
function remapId(arrayIndex: number) {
const fallbackId = arrayIndex.toString();
const id = nodeIndexToId[fallbackId];
if (id !== undefined) {
return id;
}
return fallbackId;
}
nodes.forEach((node: shapes.Node, index: number) => {
const id = remapId(index);
indexer.addNode({
...node,
id,
});
});
edges.forEach((e: [number, number, any]) => {
const [sourceIndex, targetIndex, edge] = e;
indexer.addEdge(edge, remapId(sourceIndex), remapId(targetIndex));
});
const queries = new shapes.GraphQueries(indexer);
return queries;
}
export type EndpointChange = {
change: {
category: string;
};
pathId: string;
path: string;
method: string;
};
export type EndpointChanges = {
data: {
endpoints: EndpointChange[];
};
};
export function buildEndpointChanges(
endpointQueries: endpoints.GraphQueries,
shapeQueries: shapes.GraphQueries,
sinceBatchCommitId?: string
): EndpointChanges {
const deltaBatchCommits = getDeltaBatchCommitsForEndpoints(
endpointQueries,
// In this case specifically, we want _all_ endpoint changes
sinceBatchCommitId || ALL_BATCH_COMMITS
);
const changes = new Changes();
for (const [_, batchCommit] of deltaBatchCommits) {
for (const { edgeType, nodes } of [
{ edgeType: 'created', nodes: batchCommit.createdInEdgeNodes().results },
{ edgeType: 'updated', nodes: batchCommit.updatedInEdgeNodes().results },
{ edgeType: 'removed', nodes: batchCommit.removedInEdgeNodes().results },
]) {
for (const node of nodes) {
if (
node instanceof endpoints.RequestNodeWrapper ||
node instanceof endpoints.ResponseNodeWrapper ||
node instanceof endpoints.QueryParametersNodeWrapper
) {
const endpoint = node.endpoint();
if (endpoint) {
let changeType: ChangeCategory = 'updated';
if (
node instanceof endpoints.RequestNodeWrapper &&
edgeType === 'created'
) {
changeType = 'added';
} else if (
node instanceof endpoints.RequestNodeWrapper &&
edgeType === 'removed'
) {
changeType = 'removed';
}
changes.captureChange(changeType, endpoint);
}
}
}
}
}
// Gather batch commit neighbors
const batchCommitNeighborIds = new Map();
[...deltaBatchCommits.values()].forEach((batchCommit: any) => {
const batchCommitId = batchCommit.result.id;
// TODO: create query for neighbors of all types
shapeQueries
.listIncomingNeighborsByType(batchCommitId, shapes.NodeType.Shape)
.results.forEach((shape: any) => {
batchCommitNeighborIds.set(shape.result.id, batchCommitId);
});
shapeQueries
.listIncomingNeighborsByType(batchCommitId, shapes.NodeType.Field)
.results.forEach((field: any) => {
batchCommitNeighborIds.set(field.result.id, batchCommitId);
});
});
// Both body nodes and query parameter nodes have rootShapeIds
const rootShapesWithEndpoint: {
rootShapeId: string;
endpoint: endpoints.EndpointNodeWrapper;
}[] = [];
for (const bodyNode of endpointQueries.listNodesByType(
endpoints.NodeType.Body
).results) {
const rootShapeId = bodyNode.value.rootShapeId;
const endpoint =
bodyNode.response()?.endpoint() || bodyNode.request()?.endpoint();
if (endpoint) {
rootShapesWithEndpoint.push({
rootShapeId,
endpoint,
});
}
}
for (const queryParamaterNode of endpointQueries.listNodesByType(
endpoints.NodeType.QueryParameters
).results) {
const rootShapeId = queryParamaterNode.value.rootShapeId;
const endpoint = queryParamaterNode.endpoint();
if (endpoint && rootShapeId) {
rootShapesWithEndpoint.push({
rootShapeId,
endpoint,
});
}
}
const filteredRootShapesWithEndpoint = rootShapesWithEndpoint.filter(
({ rootShapeId }) => {
if (batchCommitNeighborIds.has(rootShapeId)) {
return true;
}
// TODO this does not handle array children and polymorphic type changes
for (const descendant of shapeQueries.descendantsIterator(rootShapeId)) {
if (batchCommitNeighborIds.has(descendant.id)) {
return true;
}
}
return false;
}
);
filteredRootShapesWithEndpoint.forEach(({ endpoint }) => {
changes.captureChange('updated', endpoint);
});
return changes.toEndpointChanges();
}
type ChangeCategory = 'added' | 'updated' | 'removed';
class Changes {
public changes: Map<string, EndpointChange>;
constructor() {
this.changes = new Map();
}
captureChange(
category: ChangeCategory,
endpoint: endpoints.EndpointNodeWrapper
): boolean {
if (this.changes.has(endpoint.value.id)) return false;
this.changes.set(endpoint.value.id, {
change: { category },
pathId: endpoint.path().value.pathId,
path: endpoint.path().absolutePathPatternWithParameterNames,
method: endpoint.value.httpMethod,
});
return true;
}
toEndpointChanges(): EndpointChanges {
return {
data: {
endpoints: Array.from(this.changes.values()),
},
};
}
}
export function getEndpointGraphNodeChange(
endpointQueries: endpoints.GraphQueries,
nodeId: string,
sinceBatchCommitId?: string
): ChangeResult {
const results = {
added: false,
changed: false,
removed: false,
};
const deltaBatchCommits = getDeltaBatchCommitsForEndpoints(
endpointQueries,
sinceBatchCommitId
);
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of endpointQueries.listOutgoingNeighborsByEdgeType(
nodeId,
endpoints.EdgeType.CreatedIn
).results) {
if (node.result.id === batchCommitId) return { ...results, added: true };
}
for (const node of endpointQueries.listOutgoingNeighborsByEdgeType(
nodeId,
endpoints.EdgeType.UpdatedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, changed: true };
}
for (const node of endpointQueries.listOutgoingNeighborsByEdgeType(
nodeId,
endpoints.EdgeType.RemovedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, removed: true };
}
}
return results;
}
export function getFieldChanges(
shapeQueries: shapes.GraphQueries,
fieldId: string,
shapeId: string,
sinceBatchCommitId?: string
): ChangeResult {
const results = {
added: false,
changed: false,
removed: false,
};
const deltaBatchCommits = getDeltaBatchCommitsForShapes(
shapeQueries,
sinceBatchCommitId
);
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
fieldId,
shapes.EdgeType.CreatedIn
).results) {
if (node.result.id === batchCommitId) return { ...results, added: true };
}
}
// This will not deal with array item changes
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
fieldId,
shapes.EdgeType.UpdatedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, changed: true };
}
}
// If a field is an array, there may be changes related to the shape but not
// the field itself.
return checkForArrayChanges(
shapeQueries,
deltaBatchCommits,
results,
shapeId
);
}
export function getArrayChanges(
shapeQueries: shapes.GraphQueries,
shapeId: string,
sinceBatchCommitId?: string
): ChangeResult {
const results = {
added: false,
changed: false,
removed: false,
};
const deltaBatchCommits = getDeltaBatchCommitsForShapes(
shapeQueries,
sinceBatchCommitId
);
return checkForArrayChanges(
shapeQueries,
deltaBatchCommits,
results,
shapeId
);
}
function checkForArrayChanges(
shapeQueries: shapes.GraphQueries,
deltaBatchCommits: any,
results: ChangeResult,
shapeId: string
): ChangeResult {
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
shapeId,
shapes.EdgeType.CreatedIn
).results) {
if (node.result.id === batchCommitId) return { ...results, added: true };
}
}
// This will not deal with array item changes
for (const batchCommitId of deltaBatchCommits.keys()) {
for (const node of shapeQueries.listOutgoingNeighborsByEdgeType(
shapeId,
shapes.EdgeType.UpdatedIn
).results) {
if (node.result.id === batchCommitId)
return { ...results, changed: true };
}
}
return results;
}
type ChangeResult = {
added: boolean;
changed: boolean;
removed: boolean;
};
const ALL_BATCH_COMMITS = 'ALL_BATCH_COMMITS';
function getDeltaBatchCommitsForEndpoints(
endpointQueries: endpoints.GraphQueries,
sinceBatchCommitId?: string
): Map<string, endpoints.BatchCommitNodeWrapper> {
const deltaBatchCommits: Map<
string,
endpoints.BatchCommitNodeWrapper
> = new Map();
if (!sinceBatchCommitId) {
return deltaBatchCommits;
}
let sortedBatchCommits = endpointQueries
.listNodesByType(endpoints.NodeType.BatchCommit)
.results.sort((a: any, b: any) => {
return a.result.data.createdAt < b.result.data.createdAt ? 1 : -1;
});
const sinceBatchCommit: any = endpointQueries.findNodeById(
sinceBatchCommitId
)!;
sortedBatchCommits
.filter(
(batchCommit: any) =>
sinceBatchCommitId === ALL_BATCH_COMMITS ||
batchCommit.result.data.createdAt >
sinceBatchCommit!.result.data.createdAt
)
.forEach((batchCommit: any) => {
deltaBatchCommits.set(batchCommit.result.id, batchCommit);
});
return deltaBatchCommits;
}
function getDeltaBatchCommitsForShapes(
shapeQueries: shapes.GraphQueries,
sinceBatchCommitId?: string
): Map<string, shapes.BatchCommitNodeWrapper> {
const deltaBatchCommits: Map<
string,
shapes.BatchCommitNodeWrapper
> = new Map();
if (!sinceBatchCommitId) {
return deltaBatchCommits;
}
let sortedBatchCommits = shapeQueries
.listNodesByType(shapes.NodeType.BatchCommit)
.results.sort((a: any, b: any) => {
return a.result.data.createdAt < b.result.data.createdAt ? 1 : -1;
});
const sinceBatchCommit: any = shapeQueries.findNodeById(sinceBatchCommitId)!;
sortedBatchCommits
.filter(
(batchCommit: any) =>
sinceBatchCommitId === ALL_BATCH_COMMITS ||
batchCommit.result.data.createdAt >
sinceBatchCommit!.result.data.createdAt
)
.forEach((batchCommit: any) => {
deltaBatchCommits.set(batchCommit.result.id, batchCommit);
});
return deltaBatchCommits;
}
export type ContributionsProjection = Record<string, Record<string, string>>;
export function getContributionsProjection(
spec: any,
opticEngine: any
): ContributionsProjection {
return JSON.parse(opticEngine.get_contributions_projection(spec));
}
export class CommandGenerator {
constructor(private spec: any, private opticEngine: IOpticEngine) {}
public endpoint = {
remove: (pathId: string, method: string): CQRSCommand[] => {
const specEndpointDeleteCommands = this.opticEngine.spec_endpoint_delete_commands(
this.spec,
pathId,
method
);
return JSON.parse(specEndpointDeleteCommands).commands;
},
};
public field = {
remove: (fieldId: string): CQRSCommand[] => {
const fieldRemovalCommands = this.opticEngine.spec_field_remove_commands(
this.spec,
fieldId
);
return JSON.parse(fieldRemovalCommands);
},
edit: (fieldId: string, requestedTypes: JsonType[]): CQRSCommand[] => {
const fieldEditCommands = this.opticEngine.spec_field_edit_commands(
this.spec,
fieldId,
requestedTypes,
IOpticEngineIdGenerationStrategy.UNIQUE
);
return JSON.parse(fieldEditCommands);
},
};
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/components/DiffAccessoryNavigation.tsx
|
<gh_stars>100-1000
import React from 'react';
import { makeStyles } from '@material-ui/styles';
import { Theme } from '@material-ui/core/styles';
import { useHistory } from 'react-router-dom';
import { OpticBlueReadable } from '<src>/styles';
import { Button, LinearProgress, Typography } from '@material-ui/core';
import { useSharedDiffContext } from '<src>/pages/diffs/contexts/SharedDiffContext';
import {
useDiffReviewCapturePageLink,
useDiffUndocumentedUrlsPageLink,
} from '<src>/components';
import AskForCommitMessage from './AskForCommitMessage';
export function DiffAccessoryNavigation() {
const classes = useStyles();
const {
handledCount,
hasDiffChanges,
getUndocumentedUrls,
wipPatterns,
} = useSharedDiffContext();
const diffReviewCapturePage = useDiffReviewCapturePageLink();
const undocumentedUrlsPageLink = useDiffUndocumentedUrlsPageLink();
const history = useHistory();
const [handled, total] = handledCount;
const hasChanges =
hasDiffChanges() ||
Object.values(wipPatterns).filter((pattern) => pattern.isParameterized)
.length > 0;
const numberOfUndocumented = getUndocumentedUrls().filter((i) => !i.hide)
.length;
return (
<div style={{ display: 'flex', alignItems: 'center' }}>
<div className={classes.content} style={{ marginRight: 10 }}>
<Typography
variant="overline"
className={classes.counter}
style={{ lineHeight: 1.5 }}
>
{handled}/{total} diffs handled
</Typography>
<LinearProgress
style={{ width: 150, height: 3 }}
value={(handled / total) * 100}
variant="determinate"
/>
</div>
<div className={classes.content}>
<div className={classes.counter} style={{ marginRight: 10 }}>
<Button
size="small"
disableRipple
color="primary"
onClick={() => {
history.push(diffReviewCapturePage.linkTo());
}}
>
{' '}
Show Remaining Diffs ({total - handled})
</Button>
<Button
size="small"
disableRipple
color="primary"
onClick={() => {
history.push(undocumentedUrlsPageLink.linkTo());
}}
>
{' '}
Show Undocumented URLs ({numberOfUndocumented})
</Button>
</div>
</div>
<div className={classes.content}>
<div className={classes.counter} style={{ marginRight: 10 }}>
<AskForCommitMessage hasChanges={hasChanges} />
</div>
</div>
</div>
);
}
const useStyles = makeStyles((theme: Theme) => ({
root: {
flexGrow: 1,
backgroundColor: 'transparent',
maxWidth: 800,
},
counter: {
color: OpticBlueReadable,
fontFamily: 'Ubuntu Mono',
},
content: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/components/HttpBodyPanel.tsx
|
<reponame>tony-aq/optic
import React, { FC, useEffect, useRef } from 'react';
import { IShapeRenderer } from '<src>/types';
import { ShapeRenderer } from './ShapeRenderer';
import { Panel } from './Panel';
type HttpBodyPanelProps = {
shapes: IShapeRenderer[];
location: string;
selectedFieldId?: string | null;
fieldsAreSelectable?: boolean;
setSelectedField?: (fieldId: string) => void;
};
export const HttpBodyPanel: FC<HttpBodyPanelProps> = ({
shapes,
location,
selectedFieldId,
fieldsAreSelectable,
setSelectedField,
}) => {
const contentRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (selectedFieldId && contentRef.current) {
const isContainerScrollable =
contentRef.current.scrollHeight > contentRef.current.clientHeight;
const fieldNode = contentRef.current.querySelector(
`[data-fieldid='${selectedFieldId}']`
);
if (isContainerScrollable && fieldNode) {
const scrollTopDiff =
fieldNode.getBoundingClientRect().top -
contentRef.current.getBoundingClientRect().top;
// set scroll position to the selected field being in the middle
contentRef.current.scrollTop +=
scrollTopDiff - contentRef.current.clientHeight / 2;
}
}
}, [selectedFieldId]);
return (
<Panel header={location} contentRef={contentRef}>
<ShapeRenderer
showExamples={false}
shapes={shapes}
selectedFieldId={selectedFieldId}
fieldsAreSelectable={fieldsAreSelectable}
setSelectedField={setSelectedField}
/>
</Panel>
);
};
|
tony-aq/optic
|
workspaces/api-checks/src/types.ts
|
export type CheckFunction = ({
endpointChange,
endpoint,
}: {
endpointChange: any;
endpoint: any;
}) => Promise<string | undefined>;
export type EndpointChangeChecksOptions = {
sinceBatchCommitId: string;
spectacle: any;
};
export type CheckFunctionRegistry = {
added: CheckFunction[];
updated: CheckFunction[];
removed: CheckFunction[];
};
|
tony-aq/optic
|
workspaces/ui-v2/src/hooks/useFetchEndpoints.ts
|
import { useEffect } from 'react';
import { useSpectacleContext } from '<src>/contexts/spectacle-provider';
import { endpointActions, useAppDispatch } from '<src>/store';
export const useFetchEndpoints = (batchId?: string) => {
const dispatch = useAppDispatch();
const spectacle = useSpectacleContext();
useEffect(() => {
dispatch(
endpointActions.fetchEndpoints({ spectacle, sinceBatchCommitId: batchId })
);
}, [dispatch, spectacle, batchId]);
};
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/components/HighlightedLocation.tsx
|
<gh_stars>100-1000
import React, { FC } from 'react';
import { DiffLocation } from '<src>/lib/parse-diff';
import { OpticBlueReadable, SubtleBlueBackground } from '<src>/styles';
//@ts-ignore
import ScrollIntoViewIfNeeded from 'react-scroll-into-view-if-needed';
import { makeStyles } from '@material-ui/core';
import classnames from 'classnames';
type IHighlightedLocation =
| {
targetLocation?: DiffLocation;
statusCode?: undefined;
expectedLocation: Location.Query;
}
| {
targetLocation?: DiffLocation;
statusCode?: undefined;
expectedLocation: Location.Request;
}
| {
targetLocation?: DiffLocation;
statusCode: number;
expectedLocation: Location.Response;
};
export enum Location {
Request,
Response,
Query,
}
export const HighlightedLocation: FC<
IHighlightedLocation & React.HtmlHTMLAttributes<HTMLDivElement>
> = (props) => {
const { targetLocation, children } = props;
const classes = useStyles();
const matches: boolean = (() => {
if (!targetLocation) {
return false;
}
switch (props.expectedLocation) {
case Location.Request:
return !!targetLocation.getRequestDescriptor();
case Location.Response:
return (
targetLocation.getResponseDescriptor()?.statusCode ===
props.statusCode
);
case Location.Query:
return targetLocation.isQueryParameter();
default:
return false;
}
})();
if (targetLocation && matches) {
return (
<ScrollIntoViewIfNeeded
options={{
behavior: 'smooth',
scrollMode: 'if-needed',
}}
className={classnames(
classes.base,
classes.highlighted,
props.className
)}
style={{
width: '100%',
borderLeft: `2px solid ${OpticBlueReadable}`,
padding: 15,
backgroundColor: SubtleBlueBackground,
}}
>
{children}
</ScrollIntoViewIfNeeded>
);
}
return (
<div className={classnames(classes.base, props.className)}>{children}</div>
);
};
const useStyles = makeStyles((theme) => ({
highlighted: {
borderLeft: `2px solid ${OpticBlueReadable}`,
padding: 15,
backgroundColor: SubtleBlueBackground,
},
base: {
width: '100%',
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/ReviewDiffPages.tsx
|
<reponame>tony-aq/optic
import React, { useEffect, useMemo, useState } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import { unwrapResult } from '@reduxjs/toolkit';
import {
useDiffEnvironmentsRoot,
useDiffForEndpointLink,
useDiffReviewCapturePageLink,
useDiffReviewPageLink,
useDiffReviewPagePendingEndpoint,
useDiffUndocumentedUrlsPageLink,
} from '<src>/components/navigation/Routes';
import { SharedDiffStore } from '<src>/pages/diffs/contexts/SharedDiffContext';
import { PendingEndpointPageSession } from './PendingEndpointPage';
import { DiffUrlsPage } from './AddEndpointsPage';
import { ReviewEndpointDiffContainer } from './ReviewEndpointDiffPage';
import {
diffActions,
pathsActions,
selectors,
useAppDispatch,
useAppSelector,
} from '<src>/store';
import { useFetchEndpoints } from '<src>/hooks/useFetchEndpoints';
import {
CapturePageWithoutDiffOrRedirect,
CapturePageWithDiff,
} from './CapturePage';
import { PageLayout } from '<src>/components';
import { LoadingDiffReview } from '<src>/pages/diffs/components/LoadingDiffReview';
import { useCapturesService } from '<src>/hooks/useCapturesHook';
import { IOpticDiffService } from '../../../../spectacle/build';
import { useAnalytics } from '<src>/contexts/analytics';
import { useSpectacleContext } from '<src>/contexts/spectacle-provider';
export function DiffReviewPages(props: any) {
const { match } = props;
const { boundaryId } = match.params;
const analytics = useAnalytics();
const spectacle = useSpectacleContext();
const capturesService = useCapturesService();
const [diffService, setDiffService] = useState<IOpticDiffService | null>(
null
);
const dispatch = useAppDispatch();
useFetchEndpoints();
const endpointsState = useAppSelector((state) => state.endpoints.results);
useEffect(() => {
(async () => {
const startTime = Date.now();
const actionResult = await dispatch(
diffActions.fetchDiffsForCapture({
capturesService,
captureId: boundaryId,
})
);
try {
// unwrapResult throws an error if the thunk is rejected - we handle this in the redux layer
// we just cannot continue if there is an error
const results = unwrapResult(actionResult);
const endTime = Date.now();
setDiffService(results.diffService);
analytics.reviewPageLoaded(
results.data.diffs.length,
results.data.urls.length,
endTime - startTime,
results.numberOfEndpoints
);
} catch (e) {}
})();
}, [dispatch, capturesService, boundaryId, analytics]);
const diffState = useAppSelector((state) => state.diff.state);
const filteredEndpoints = useMemo(
() => selectors.filterRemovedItems(endpointsState.data?.endpoints || []),
[endpointsState.data]
);
useEffect(() => {
dispatch(
pathsActions.fetchPaths({
spectacle,
})
);
}, [dispatch, spectacle]);
const pathsState = useAppSelector((state) => state.paths.results);
const diffUndocumentedUrlsPageLink = useDiffUndocumentedUrlsPageLink();
const diffReviewCapturePageLink = useDiffReviewCapturePageLink();
const diffForEndpointLink = useDiffForEndpointLink();
const diffReviewPagePendingEndpoint = useDiffReviewPagePendingEndpoint();
if (
diffState.loading ||
endpointsState.loading ||
pathsState.loading ||
!diffService
) {
return (
<PageLayout>
<LoadingDiffReview />
</PageLayout>
);
}
if (diffState.error || endpointsState.error || pathsState.error) {
return <>error loading diff page</>;
}
return (
<SharedDiffStore
diffService={diffService}
diffs={diffState.data.diffs}
diffTrails={diffState.data.trails}
urls={diffState.data.urls}
captureId={boundaryId}
endpoints={filteredEndpoints}
allPaths={pathsState.data}
>
<Switch>
<Route
exact
path={diffReviewCapturePageLink.path}
component={CapturePageWithDiff}
/>
<Route
exact
path={diffUndocumentedUrlsPageLink.path}
component={DiffUrlsPage}
/>
<Route
exact
path={diffForEndpointLink.path}
component={ReviewEndpointDiffContainer}
/>
<Route
exact
path={diffReviewPagePendingEndpoint.path}
component={PendingEndpointPageSession}
/>
<Redirect to={diffReviewCapturePageLink.linkTo()} />
</Switch>
</SharedDiffStore>
);
}
export function DiffReviewEnvironments(props: any) {
const diffRoot = useDiffReviewPageLink();
const diffEnvironmentsRoot = useDiffEnvironmentsRoot();
return (
<Switch>
<Route
path={diffRoot.path}
exact
component={CapturePageWithoutDiffOrRedirect}
/>
<Route path={diffEnvironmentsRoot.path} component={DiffReviewPages} />
<Redirect to={diffRoot.path} />
</Switch>
);
}
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ShapeRenderer/ShapeRenderContext.tsx
|
<filename>workspaces/ui-v2/src/components/ShapeRenderer/ShapeRenderContext.tsx
import React, { useEffect } from 'react';
import { IShapeRenderer } from '<src>/types';
import { useContext, useState, useCallback } from 'react';
import { DepthStore } from './DepthContext';
import { OneOfTabsProps } from './OneOfTabs';
type IShapeRenderContext = {
selectedFieldId?: string | null;
showExamples: boolean;
fieldsAreSelectable: boolean;
getChoice: (branch: OneOfTabsProps) => string;
updateChoice: (shapeId: string, branchId: string) => void;
selectField: (fieldId: string) => void;
};
export const ShapeRenderContext = React.createContext<IShapeRenderContext | null>(
null
);
type ShapeRenderContextProps = {
children: React.ReactNode;
shapes: IShapeRenderer[];
showExamples: boolean;
selectedFieldId?: string | null;
fieldsAreSelectable?: boolean;
setSelectedField?: (fieldId: string) => void;
};
// Returns the choices that should be made for a field to be visible
// This is for polymorphic shapes where it's not immediately obvious how a field is nested
const getChoicesFromSelectedField = (
fieldId: string,
shapes: IShapeRenderer[]
): {
shapeId: string;
branchId: string;
}[] => {
const stack: {
shapeId: string;
shapes: IShapeRenderer[];
choices: {
shapeId: string;
branchId: string;
}[];
}[] = [
{
shapeId: 'root',
shapes: shapes,
choices: [],
},
];
while (stack.length > 0) {
const { shapeId, shapes, choices } = stack.pop()!;
const hasMultipleChoices = shapes.length > 1;
for (const shape of shapes) {
const newChoices = hasMultipleChoices
? [
...choices,
{
shapeId: shapeId,
branchId: shape.shapeId,
},
]
: [...choices];
if (shape.asObject) {
for (const field of shape.asObject.fields) {
if (field.fieldId === fieldId) {
return newChoices;
}
stack.push({
choices: newChoices,
shapes: field.shapeChoices,
shapeId: field.shapeId,
});
}
} else if (shape.asArray) {
stack.push({
choices: newChoices,
shapes: shape.asArray.shapeChoices,
shapeId: shape.asArray.shapeId,
});
}
}
}
return [];
};
export const ShapeRenderStore = ({
children,
shapes,
showExamples,
selectedFieldId,
fieldsAreSelectable,
setSelectedField,
}: ShapeRenderContextProps) => {
const [selectedOneOfChoices, updateSelectedOneOfChoices] = useState<{
[key: string]: string;
}>({});
useEffect(() => {
if (selectedFieldId) {
const choicesForVisibleField = getChoicesFromSelectedField(
selectedFieldId,
shapes
);
updateSelectedOneOfChoices((previousChoices) => {
const newChoices = {
...previousChoices,
};
for (const choice of choicesForVisibleField) {
newChoices[choice.shapeId] = choice.branchId;
}
return newChoices;
});
}
}, [shapes, selectedFieldId]);
const getChoice = (branch: OneOfTabsProps) => {
if (selectedOneOfChoices[branch.shapeId]) {
return selectedOneOfChoices[branch.shapeId];
} else {
return branch.choices[0].id;
}
};
const updateChoice = (shapeId: string, branchId: string) => {
updateSelectedOneOfChoices((previousChoices) => ({
...previousChoices,
[shapeId]: branchId,
}));
};
const selectField = useCallback(
(fieldId) => {
if (setSelectedField) setSelectedField(fieldId);
},
[setSelectedField]
);
return (
<ShapeRenderContext.Provider
value={{
showExamples,
getChoice,
updateChoice,
selectedFieldId,
selectField,
fieldsAreSelectable: !!fieldsAreSelectable,
}}
>
<DepthStore depth={0}>{children}</DepthStore>
</ShapeRenderContext.Provider>
);
};
export function useShapeRenderContext() {
const value = useContext(ShapeRenderContext);
if (!value) {
throw new Error('Could not find ShapeRendererContext');
}
return value;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/EndpointRootPage.tsx
|
<reponame>tony-aq/optic
import React, { FC, useCallback, useEffect, useState } from 'react';
import { Redirect, RouteComponentProps } from 'react-router-dom';
import { Button, LinearProgress, makeStyles } from '@material-ui/core';
import { Alert } from '@material-ui/lab';
import { Delete as DeleteIcon, Undo as UndoIcon } from '@material-ui/icons';
import { JsonType } from '@useoptic/optic-domain';
import {
EndpointName,
PathParameters,
PageLayout,
FullWidth,
ContributionsList,
QueryParametersPanel,
ShapeFetcher,
HttpBodyPanel,
HttpBodySelector,
Panel,
HighlightController,
FieldViewer,
} from '<src>/components';
import { useDocumentationPageLink } from '<src>/components/navigation/Routes';
import { FontFamily, SubtleBlueBackground } from '<src>/styles';
import {
useAppSelector,
useAppDispatch,
selectors,
documentationEditActions,
} from '<src>/store';
import { IShapeRenderer } from '<src>/types';
import { getEndpointId } from '<src>/utils';
import { useRunOnKeypress } from '<src>/hooks/util';
import {
EndpointTOC,
DocsFieldOrParameterContribution,
EndpointNameContribution,
DocsPageAccessoryNavigation,
MarkdownBodyContribution,
DeleteEndpointConfirmationModal,
SimulatedBody,
ShapeEditor,
} from '<src>/pages/docs/components';
import { useAnalytics } from '<src>/contexts/analytics';
export const EndpointRootPageWithDocsNav: FC<
React.ComponentProps<typeof EndpointRootPage>
> = (props) => (
<PageLayout AccessoryNavigation={DocsPageAccessoryNavigation}>
<EndpointRootPage {...props} />
</PageLayout>
);
export const EndpointRootPage: FC<
RouteComponentProps<{
pathId: string;
method: string;
}>
> = ({ match }) => {
const analytics = useAnalytics();
const documentationPageLink = useDocumentationPageLink();
const endpointsState = useAppSelector((state) => state.endpoints.results);
const isEditing = useAppSelector(
(state) => state.documentationEdits.isEditing
);
const pendingCount = useAppSelector(
selectors.getDocumentationEditStagedCount
);
const dispatch = useAppDispatch();
const { pathId, method } = match.params;
const thisEndpoint = useAppSelector(
selectors.getEndpoint({ pathId, method })
);
const userRemovedFields = useAppSelector(
(state) => state.documentationEdits.fields.removed
);
const allRemovedFields = useAppSelector(
selectors.memoizedGetAllRemovedFields
);
const isEndpointRemoved = thisEndpoint ? thisEndpoint.isRemoved : false;
const onKeyPress = useRunOnKeypress(
() => {
if (isEditing && pendingCount > 0) {
dispatch(
documentationEditActions.updateCommitModalState({
commitModalOpen: true,
})
);
}
},
{
keys: new Set(['Enter']),
inputTagNames: new Set(['input']),
}
);
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const endpointId = getEndpointId({ method, pathId });
useEffect(() => {
analytics.documentationListPageLoaded();
}, [analytics]);
const isEndpointStagedForDeletion = useAppSelector(
selectors.isEndpointRemoved({ method, pathId })
);
const removeEndpoint = () =>
dispatch(documentationEditActions.removeEndpoint({ method, pathId }));
const unremoveEndpoint = () =>
dispatch(documentationEditActions.unremoveEndpoint({ method, pathId }));
const isFieldRemoved = useCallback(
(fieldId: string) => {
if (userRemovedFields.includes(fieldId)) {
return 'root_removed';
} else if (allRemovedFields.has(fieldId)) {
return 'removed';
} else {
return 'not_removed';
}
},
[userRemovedFields, allRemovedFields]
);
const onToggleRemovedField = useCallback(
(fieldId: string) => {
if (userRemovedFields.includes(fieldId)) {
dispatch(documentationEditActions.unremoveField({ fieldId }));
} else {
dispatch(documentationEditActions.removeField({ fieldId }));
}
},
[userRemovedFields, dispatch]
);
const onChangeFieldType = useCallback(
(
fieldId: string,
requestedFieldTypes: Set<JsonType>,
isFieldTypeDifferent: boolean
) => {
if (isFieldTypeDifferent) {
dispatch(
documentationEditActions.addFieldEdit({
fieldId,
options: {
isOptional: requestedFieldTypes.has(JsonType.UNDEFINED),
isNullable: requestedFieldTypes.has(JsonType.NULL),
},
})
);
} else {
dispatch(
documentationEditActions.removeFieldEdit({
fieldId,
})
);
}
},
[dispatch]
);
const onFieldDescriptionChanged = useCallback(
(fieldId: string, description: string, isDescriptionDifferent: boolean) => {
if (isDescriptionDifferent) {
dispatch(
documentationEditActions.addContribution({
id: fieldId,
contributionKey: 'description',
value: description,
endpointId: endpointId,
})
);
} else {
dispatch(
documentationEditActions.removeContribution({
id: fieldId,
contributionKey: 'description',
})
);
}
},
[endpointId, dispatch]
);
const classes = useStyles();
if (endpointsState.loading) {
return <LinearProgress variant="indeterminate" />;
}
if (!thisEndpoint) {
return <>no endpoint here</>;
}
if (isEndpointRemoved) {
return <Redirect to={documentationPageLink.linkTo()} />;
}
const parameterizedPathParts = thisEndpoint.pathParameters.filter(
(path) => path.isParameterized
);
const visibleQueryParameters =
thisEndpoint.query && selectors.isItemVisible(thisEndpoint.query)
? thisEndpoint.query
: null;
const visibleRequests = selectors.filterRemovedItems(thisEndpoint.requests);
const visibleResponsesByStatusCode = selectors.filterMapOfRemovedItems(
thisEndpoint.responsesByStatusCode
);
return (
<>
{deleteModalOpen && (
<DeleteEndpointConfirmationModal
endpoint={thisEndpoint}
handleClose={() => setDeleteModalOpen(false)}
handleConfirm={() => {
removeEndpoint();
setDeleteModalOpen(false);
}}
/>
)}
{isEndpointStagedForDeletion && isEditing && (
<Alert severity="warning" className={classes.deleteInfoHeader}>
This endpoint is staged to be deleted
</Alert>
)}
<FullWidth
style={{ paddingTop: 30, paddingBottom: 400 }}
onKeyPress={onKeyPress}
>
<EndpointNameContribution
id={endpointId}
contributionKey="purpose"
defaultText="What does this endpoint do?"
initialValue={thisEndpoint.purpose}
endpoint={{
pathId,
method,
}}
/>
<div className={classes.endpointNameContainer}>
<EndpointName
fontSize={19}
leftPad={0}
method={thisEndpoint.method}
fullPath={thisEndpoint.fullPath}
/>
{isEditing &&
(isEndpointStagedForDeletion ? (
<Button
variant="outlined"
color="secondary"
onClick={() => {
unremoveEndpoint();
}}
>
Undelete <UndoIcon className={classes.icon} />
</Button>
) : (
<Button
variant="outlined"
color="secondary"
onClick={() => {
setDeleteModalOpen(true);
}}
>
Delete <DeleteIcon className={classes.icon} />
</Button>
))}
</div>
<div className={classes.bodyContainer}>
<div className={classes.bodyDetails}>
<div>
<MarkdownBodyContribution
id={endpointId}
contributionKey={'description'}
defaultText={'Describe this endpoint'}
initialValue={thisEndpoint.description}
endpoint={{
pathId,
method,
}}
/>
</div>
<div className={classes.panel}>
<Panel
header={
<EndpointName
fontSize={14}
leftPad={0}
method={thisEndpoint.method}
fullPath={thisEndpoint.fullPath}
/>
}
>
<PathParameters
parameters={parameterizedPathParts}
renderField={(param) => {
const alwaysAString: IShapeRenderer = {
shapeId: param.id + 'shape',
jsonType: JsonType.STRING,
};
return (
<DocsFieldOrParameterContribution
key={param.id}
endpoint={{
pathId,
method,
}}
id={param.id}
name={param.name}
shapes={[alwaysAString]}
depth={0}
initialValue={param.description}
required
/>
);
}}
/>
<div
style={{
marginTop: 10,
backgroundColor: SubtleBlueBackground,
borderTop: '1px solid #e2e2e2',
}}
>
<EndpointTOC
query={visibleQueryParameters}
requests={visibleRequests}
responsesByStatusCode={visibleResponsesByStatusCode}
/>
</div>
</Panel>
</div>
</div>
</div>
{visibleQueryParameters && (
<div className={classes.bodyContainer} id="query-parameters">
<div className={classes.bodyHeaderContainer}>
<h6 className={classes.bodyHeader}>Query Parameters</h6>
</div>
<div className={classes.bodyContributionContainer}>
<MarkdownBodyContribution
id={visibleQueryParameters.queryParametersId}
contributionKey={'description'}
defaultText={'Add a description'}
initialValue={visibleQueryParameters.description}
endpoint={thisEndpoint}
/>
</div>
<ShapeFetcher
rootShapeId={visibleQueryParameters.rootShapeId}
endpointId={endpointId}
>
{(shapes, fields) => (
<HighlightController>
{(selectedFieldId, setSelectedFieldId) => (
<div className={classes.bodyDetails}>
<div>
{process.env.REACT_APP_FF_FIELD_LEVEL_EDITS !==
'true' ? (
<ContributionsList
renderField={(field) => {
const fieldWithoutArrayShape = selectors.removeArrayShapeFromField(
field
);
return (
<DocsFieldOrParameterContribution
key={
fieldWithoutArrayShape.contribution.id +
fieldWithoutArrayShape.contribution
.contributionKey
}
endpoint={{
pathId,
method,
}}
name={fieldWithoutArrayShape.name}
shapes={fieldWithoutArrayShape.shapes}
depth={fieldWithoutArrayShape.depth}
id={fieldWithoutArrayShape.contribution.id}
initialValue={
fieldWithoutArrayShape.contribution.value
}
required={fieldWithoutArrayShape.required}
/>
);
}}
fieldDetails={fields}
/>
) : isEditing ? (
<ShapeEditor
fields={fields.map(
selectors.removeArrayShapeFromField
)}
selectedFieldId={selectedFieldId}
setSelectedField={setSelectedFieldId}
nonEditableTypes={new Set([JsonType.NULL])}
onChangeDescription={onFieldDescriptionChanged}
onChangeFieldType={onChangeFieldType}
isFieldRemoved={isFieldRemoved}
onToggleRemove={onToggleRemovedField}
/>
) : (
<FieldViewer fields={fields} />
)}
</div>
<div className={classes.panel}>
{isEditing ? (
<SimulatedBody
rootShapeId={visibleQueryParameters.rootShapeId}
endpointId={endpointId}
>
{(shapes) => (
<QueryParametersPanel
parameters={selectors.convertShapeToQueryParameters(
shapes
)}
/>
)}
</SimulatedBody>
) : (
<QueryParametersPanel
parameters={selectors.convertShapeToQueryParameters(
shapes
)}
/>
)}
</div>
</div>
)}
</HighlightController>
)}
</ShapeFetcher>
</div>
)}
{visibleRequests.length > 0 && (
<div className={classes.bodyContainer} id="request-body">
<div className={classes.bodyHeaderContainer}>
<h6 className={classes.bodyHeader}>Request Body</h6>
</div>
<HttpBodySelector
items={visibleRequests}
getDisplayName={(request) =>
request.body?.contentType || 'No Body'
}
>
{(request) => (
<>
<div className={classes.bodyContributionContainer}>
<MarkdownBodyContribution
id={request.requestId}
contributionKey={'description'}
defaultText={'Add a description'}
initialValue={request.description}
endpoint={thisEndpoint}
/>
</div>
{request.body ? (
<ShapeFetcher
rootShapeId={request.body.rootShapeId}
endpointId={endpointId}
>
{(shapes, fields) => (
<HighlightController>
{(selectedFieldId, setSelectedFieldId) => (
<div className={classes.bodyDetails}>
<div>
{process.env.REACT_APP_FF_FIELD_LEVEL_EDITS !==
'true' ? (
<ContributionsList
renderField={(field) => (
<DocsFieldOrParameterContribution
key={
field.contribution.id +
field.contribution.contributionKey
}
endpoint={{
pathId,
method,
}}
name={field.name}
shapes={field.shapes}
depth={field.depth}
id={field.fieldId}
initialValue={field.contribution.value}
required={field.required}
setSelectedField={setSelectedFieldId}
/>
)}
fieldDetails={fields}
/>
) : isEditing ? (
<ShapeEditor
fields={fields}
selectedFieldId={selectedFieldId}
setSelectedField={setSelectedFieldId}
onChangeDescription={
onFieldDescriptionChanged
}
onChangeFieldType={onChangeFieldType}
isFieldRemoved={isFieldRemoved}
onToggleRemove={onToggleRemovedField}
/>
) : (
<FieldViewer fields={fields} />
)}
</div>
<div className={classes.panel}>
{isEditing ? (
<SimulatedBody
rootShapeId={request.body!.rootShapeId}
endpointId={endpointId}
>
{(shapes) => (
<HttpBodyPanel
shapes={shapes}
location={request.body!.contentType}
selectedFieldId={selectedFieldId}
fieldsAreSelectable={true}
setSelectedField={setSelectedFieldId}
/>
)}
</SimulatedBody>
) : (
<HttpBodyPanel
shapes={shapes}
location={request.body!.contentType}
/>
)}
</div>
</div>
)}
</HighlightController>
)}
</ShapeFetcher>
) : (
<>No Body Request</>
)}
</>
)}
</HttpBodySelector>
</div>
)}
{selectors
.getResponsesInSortedOrder(visibleResponsesByStatusCode)
.map(([statusCode, responses]) => (
<div
className={classes.bodyContainer}
id={statusCode}
key={statusCode}
>
<div className={classes.bodyHeaderContainer}>
<h6 className={classes.bodyHeader}>{statusCode} Response</h6>
</div>
<HttpBodySelector
items={responses}
getDisplayName={(response) =>
response.body?.contentType || 'No Body'
}
>
{(response) => (
<>
<div className={classes.bodyContributionContainer}>
<MarkdownBodyContribution
id={response.responseId}
contributionKey={'description'}
defaultText={'Add a description'}
initialValue={response.description}
endpoint={thisEndpoint}
/>
</div>
{response.body ? (
<ShapeFetcher
rootShapeId={response.body.rootShapeId}
endpointId={endpointId}
>
{(shapes, fields) => (
<HighlightController>
{(selectedFieldId, setSelectedFieldId) => (
<div className={classes.bodyDetails}>
<div>
{process.env
.REACT_APP_FF_FIELD_LEVEL_EDITS !==
'true' ? (
<ContributionsList
renderField={(field) => (
<DocsFieldOrParameterContribution
key={
field.contribution.id +
field.contribution.contributionKey
}
endpoint={{
pathId,
method,
}}
name={field.name}
shapes={field.shapes}
depth={field.depth}
id={field.fieldId}
initialValue={
field.contribution.value
}
required={field.required}
setSelectedField={setSelectedFieldId}
/>
)}
fieldDetails={fields}
/>
) : isEditing ? (
<ShapeEditor
fields={fields}
selectedFieldId={selectedFieldId}
setSelectedField={setSelectedFieldId}
onChangeDescription={
onFieldDescriptionChanged
}
onChangeFieldType={onChangeFieldType}
isFieldRemoved={isFieldRemoved}
onToggleRemove={onToggleRemovedField}
/>
) : (
<FieldViewer fields={fields} />
)}
</div>
<div className={classes.panel}>
{isEditing ? (
<SimulatedBody
rootShapeId={response.body!.rootShapeId}
endpointId={endpointId}
>
{(shapes) => (
<HttpBodyPanel
shapes={shapes}
location={response.body!.contentType}
selectedFieldId={selectedFieldId}
fieldsAreSelectable={true}
setSelectedField={setSelectedFieldId}
/>
)}
</SimulatedBody>
) : (
<HttpBodyPanel
shapes={shapes}
location={response.body!.contentType}
/>
)}
</div>
</div>
)}
</HighlightController>
)}
</ShapeFetcher>
) : (
<>No Body Request</>
)}
</>
)}
</HttpBodySelector>
</div>
))}
</FullWidth>
</>
);
};
const useStyles = makeStyles((theme) => ({
endpointNameContainer: {
display: 'flex',
alignItems: 'center',
width: '100%',
justifyContent: 'space-between',
padding: '16px 0',
},
icon: {
paddingLeft: theme.spacing(1),
},
deleteInfoHeader: {
justifyContent: 'center',
display: 'fixed',
},
bodyContainer: {
marginTop: theme.spacing(6),
width: '100%',
height: '100%',
},
bodyHeaderContainer: {},
bodyContributionContainer: {
marginBottom: theme.spacing(2),
},
bodyHeader: {
fontSize: '1.25rem',
fontFamily: FontFamily,
fontWeight: 500,
lineHeight: 1.6,
letterSpacing: '0.0075em',
margin: theme.spacing(3, 0),
},
bodyDetails: {
display: 'flex',
width: '100%',
height: '100%',
'& > div': {
width: '50%',
padding: theme.spacing(0, 1),
},
},
panel: {
position: 'sticky',
top: 50,
alignSelf: 'flex-start',
},
}));
|
tony-aq/optic
|
workspaces/spectacle/src/openapi/index.ts
|
import { OperationDefinitionNode } from 'graphql';
import { JsonSchema, jsonSchemaFromShapeId } from './json-schema';
export async function generateOpenApi(spectacle: any) {
const requests = await spectacle.queryWrapper({
query: `{
requests {
id
pathId
pathComponents {
name
isParameterized
contributions
}
absolutePathPatternWithParameterNames
pathContributions
requestContributions
method
bodies {
contentType
rootShapeId
}
responses {
id
statusCode
contributions
bodies {
contentType
rootShapeId
}
}
}
}`,
variables: {},
});
const openapi: OpenApi = {
openapi: '3.0.3',
info: {
title: 'Optic Generated OpenAPI',
version: '1.0.0',
},
paths: {},
};
for (const request of requests.data.requests) {
const path = request.absolutePathPatternWithParameterNames;
if (!(path in openapi.paths)) {
openapi.paths[path] = {};
}
for (const pathComponent of request.pathComponents || []) {
if (pathComponent.isParameterized) {
if (!('parameters' in openapi.paths[path]))
openapi.paths[path].parameters = [];
const pathParam: Parameter = {
name: pathComponent.name,
in: 'path',
schema: {
type: 'string',
},
required: true,
};
if ('description' in pathComponent.contributions) {
pathParam.description = pathComponent.contributions.description;
}
openapi.paths[path].parameters?.push(pathParam);
}
}
switch (request.method) {
case 'GET':
openapi.paths[path].get = await buildOperation(spectacle, request);
break;
case 'POST':
openapi.paths[path].post = await buildOperation(spectacle, request);
break;
case 'PUT':
openapi.paths[path].put = await buildOperation(spectacle, request);
break;
case 'PATCH':
openapi.paths[path].patch = await buildOperation(spectacle, request);
break;
case 'DELETE':
openapi.paths[path].delete = await buildOperation(spectacle, request);
break;
}
}
return openapi;
}
async function buildOperation(
spectacle: any,
request: any
): Promise<Operation> {
const operation: Operation = {};
if ('summary' in request.pathContributions) {
operation.summary = request.pathContributions.purpose;
}
if ('description' in request.pathContributions) {
operation.description = request.pathContributions.description;
}
for (const requestBody of request.bodies || []) {
if (!operation.requestBody) operation.requestBody = { content: {} };
const schema = await jsonSchemaFromShapeId(
spectacle,
requestBody.rootShapeId
);
operation.requestBody.content[requestBody.contentType] = { schema };
}
for (const response of request.responses || []) {
if (!operation.responses) operation.responses = {};
const description =
'description' in response.contributions
? response.contributions.description
: '';
operation.responses[response.statusCode] = { description, content: {} };
for (const responseBody of response.bodies || []) {
const schema = await jsonSchemaFromShapeId(
spectacle,
responseBody.rootShapeId
);
operation.responses[response.statusCode].content[
responseBody.contentType
] = { schema };
}
}
return operation;
}
type OpenApi = {
openapi: '3.0.3';
info: {
title: string;
version: string;
};
paths: {
[property: string]: PathItem;
};
};
type PathItem = {
parameters?: Parameter[];
get?: Operation;
post?: Operation;
put?: Operation;
patch?: Operation;
delete?: Operation;
};
type Parameter = {
description?: string;
name: string;
in: string;
schema: {
type: 'string';
};
required: true;
};
type Operation = {
summary?: string;
description?: string;
requestBody?: {
content: {
[property: string]: MediaType;
};
};
responses?: {
[property: string]: {
description: '';
content: {
[property: string]: MediaType;
};
};
};
};
type MediaType = {
schema: JsonSchema;
};
|
tony-aq/optic
|
workspaces/ui-v2/src/utils/dateFormat.ts
|
<filename>workspaces/ui-v2/src/utils/dateFormat.ts
// @ts-ignore
import TimeAgo from 'javascript-time-ago';
// @ts-ignore
import en from 'javascript-time-ago/locale/en';
TimeAgo.addLocale(en);
const timeAgo = new TimeAgo('en-US');
export const formatTimeAgo = (date: Date) => {
return timeAgo.format(new Date(date));
};
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/diffs/hooks/useEndpointDiffs.ts
|
<gh_stars>100-1000
import { useSharedDiffContext } from '../contexts/SharedDiffContext';
import { EndpointDiffGrouping } from '../contexts/SharedDiffState';
export function useEndpointDiffs(
pathId: string,
method: string
): EndpointDiffGrouping {
const diffState = useSharedDiffContext();
const endpoint = diffState.context.results.diffsGroupedByEndpoint.find(
(i) => i.pathId === pathId && i.method === method
)!;
return endpoint;
}
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/docs/components/EndpointTOC.tsx
|
<gh_stars>100-1000
import * as React from 'react';
import makeStyles from '@material-ui/styles/makeStyles';
import { getReasonPhrase } from 'http-status-codes';
import { List, ListItem, Typography } from '@material-ui/core';
import { selectors } from '<src>/store';
import { SubtleGreyBackground } from '<src>/styles';
import { IQueryParameters, IRequest, IEndpoint } from '<src>/types';
import { goToAnchor } from '<src>/utils';
export type EndpointTOCProps = {
query: IQueryParameters | null;
requests: IRequest[];
responsesByStatusCode: IEndpoint['responsesByStatusCode'];
};
function Code({ value }: { value: string }) {
return (
<span
style={{
backgroundColor: SubtleGreyBackground,
paddingLeft: 4,
paddingRight: 4,
}}
>
{value}
</span>
);
}
export function EndpointTOC(props: EndpointTOCProps) {
const classes = useStyles();
return (
<List dense>
{props.query === null &&
props.requests.length === 0 &&
Object.keys(props.responsesByStatusCode).length === 0 ? (
<Typography className={classes.none}>No bodies documented.</Typography>
) : null}
{props.query && (
<EndpointTOCRow
label={'Query Parameters'}
anchorLink="query-parameters"
detail={<></>}
/>
)}
{props.requests.length > 0 && (
<EndpointTOCRow
label={'Request Body'}
anchorLink={'request-body'}
detail={
<>
consumes{' '}
{props.requests.length > 1 ? (
<>{props.requests.length} content types</>
) : (
<Code
value={props.requests[0].body?.contentType || 'No Body'}
/>
)}
</>
}
/>
)}
{selectors
.getResponsesInSortedOrder(props.responsesByStatusCode)
.map(([statusCode, responses]) => {
return (
<EndpointTOCRow
label={`${getReasonPhrase(statusCode)} - ${statusCode} Response`}
anchorLink={statusCode}
key={statusCode}
detail={
<>
produces{' '}
{responses.length > 1 ? (
<>{responses.length} content types</>
) : (
<Code value={responses[0].body?.contentType || 'No Body'} />
)}
</>
}
/>
);
})}
</List>
);
}
export type EndpointTOCRowProps = {
label: string;
anchorLink: string;
detail: any;
};
export function EndpointTOCRow({
label,
detail,
anchorLink,
}: EndpointTOCRowProps) {
const classes = useStyles();
return (
<ListItem className={classes.row} button onClick={goToAnchor(anchorLink)}>
<div className={classes.leftContent}>{label}</div>
<div className={classes.rightContent}> {detail}</div>
</ListItem>
);
}
const useStyles = makeStyles((theme) => ({
container: {
maxWidth: 400,
},
row: {
display: 'flex',
flexDirection: 'row',
},
leftContent: {
display: 'flex',
alignItems: 'center',
justifyItems: 'center',
color: 'rgb(79, 86, 107)',
fontSize: 13,
fontWeight: 600,
justifyContent: 'flex-end',
paddingRight: 10,
fontFamily: 'Ubuntu',
},
rightContent: {
color: 'rgb(79, 86, 107)',
fontSize: 13,
flexShrink: 1,
paddingLeft: 4,
},
none: {
color: '#8792a2',
fontSize: 12,
paddingLeft: 10,
},
h6: {
fontSize: 13,
fontFamily: 'Ubuntu, Inter',
fontWeight: 500,
lineHeight: 1.6,
marginBottom: 8,
},
}));
|
tony-aq/optic
|
workspaces/ui-v2/src/contexts/spectacle-provider.tsx
|
import React, { useCallback, useContext, useEffect, useState } from 'react';
import { SpectacleInput, IForkableSpectacle } from '@useoptic/spectacle';
import * as Sentry from '@sentry/react';
import { AsyncStatus } from '<src>/types';
export const SpectacleContext = React.createContext<IForkableSpectacle | null>(
null
);
export const SpectacleStore = (props: {
spectacle: IForkableSpectacle;
children: React.ReactNode;
}) => {
return (
<SpectacleContext.Provider value={props.spectacle}>
{props.children}
</SpectacleContext.Provider>
);
};
export const useSpectacleContext = () => {
const value = useContext(SpectacleContext);
if (!value) {
throw new Error('Could not find spectacle context');
}
return value;
};
export function useSpectacleQuery<Result, Input = {}>(
input: SpectacleInput<Input>
): AsyncStatus<Result> {
const spectacle = useSpectacleContext();
const [result, setResult] = useState<AsyncStatus<Result>>({
loading: true,
});
const stringInput = JSON.stringify(input);
useEffect(() => {
async function task() {
try {
const result = await spectacle.query<Result, Input>(input);
if (result.errors) {
throw new Error(JSON.stringify(result.errors));
}
setResult({
loading: false,
// We've explicitly checked that there are no errors
data: result.data!,
});
} catch (e) {
console.error(e);
Sentry.captureException(e);
setResult({
loading: false,
error: new Error(e),
});
}
}
task();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [stringInput, spectacle]);
return result;
}
export function useSpectacleCommand(): <Result, Input = {}>(
input: SpectacleInput<Input>
) => Promise<Result> {
const spectacle = useSpectacleContext();
return useCallback(
async <Result, Input>(input: SpectacleInput<Input>): Promise<Result> => {
try {
const result = await spectacle.mutate<Result, Input>(input);
if (result.errors) {
console.error(result.errors);
throw new Error(JSON.stringify(result.errors));
}
return result.data!;
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw new Error(e);
}
},
[spectacle]
);
}
|
tony-aq/optic
|
workspaces/ui-v2/src/store/paths/thunks.ts
|
import { createAsyncThunk } from '@reduxjs/toolkit';
import * as Sentry from '@sentry/react';
import { IForkableSpectacle } from '@useoptic/spectacle';
import { IPath } from '<src>/types';
export const AllPathsQuery = `{
paths {
parentPathId
absolutePathPattern
absolutePathPatternWithParameterNames
isParameterized
name
pathId
isRemoved
}
}`;
interface PathResponse extends IPath {
isRemoved: boolean;
}
export type PathQueryResponse = {
paths: PathResponse[];
};
export const fetchPaths = createAsyncThunk<
IPath[],
{ spectacle: IForkableSpectacle }
>('FETCH_PATHS', async ({ spectacle }) => {
try {
const results = await spectacle.query<PathQueryResponse>({
query: AllPathsQuery,
variables: {},
});
if (results.errors) {
console.error(results.errors);
throw new Error(JSON.stringify(results.errors));
}
return results.data!.paths.filter((path) => !path.isRemoved);
} catch (e) {
console.error(e);
Sentry.captureException(e);
throw e;
}
});
|
tony-aq/optic
|
workspaces/ui-v2/src/components/ShapeTypeSummary.tsx
|
<filename>workspaces/ui-v2/src/components/ShapeTypeSummary.tsx
import React, { FC } from 'react';
import { JsonType } from '@useoptic/optic-domain';
import { IShapeRenderer } from '<src>/types';
import * as Theme from '<src>/styles/theme';
export const ShapeTypeSummary: FC<{
shapes: IShapeRenderer[];
required: boolean;
hasColoredFields?: boolean;
}> = ({ shapes, required, hasColoredFields }) => {
const optionalText = required ? '' : ' (optional)';
const components = shapes.map(({ jsonType }: { jsonType: JsonType }) => (
<span
key={jsonType}
style={{
color: hasColoredFields
? Theme.jsonTypeColors[jsonType]
: Theme.GrayText,
}}
>
{jsonType.toString().toLowerCase()}
</span>
));
if (shapes.length === 1) {
return (
<>
{components} {optionalText}
</>
);
} else {
const last = components.pop();
const secondToLast = components.pop();
return (
<>
{components.map((component) => (
<span key={component.key}>{component}, </span>
))}
{secondToLast} or {last} {optionalText}
</>
);
}
};
|
tony-aq/optic
|
workspaces/ui-v2/src/pages/changelog/components/index.ts
|
<gh_stars>100-1000
export * from './ChangelogAccessoryNavigation';
export * from './ValidateBatchId';
|
tony-aq/optic
|
workspaces/cli-server/src/routers/capture-router.ts
|
<filename>workspaces/cli-server/src/routers/capture-router.ts
import express from 'express';
import bodyParser from 'body-parser';
import Bottleneck from 'bottleneck';
import { IdGenerator } from '@useoptic/cli-shared';
import { CaptureId } from '@useoptic/saas-types';
import {
IInteractionPointerConverter,
LocalCaptureInteractionContext,
} from '@useoptic/cli-shared/build/captures/avro/file-system/interaction-iterator';
import { ILearnedBodies } from '@useoptic/cli-shared/build/diffs/initial-types';
import { OnDemandInitialBodyRust } from '../tasks/on-demand-initial-body-rust';
import { OnDemandShapeDiffAffordancesRust } from '../tasks/on-demand-trail-values-rust';
import * as opticEngine from '@useoptic/optic-engine-wasm';
export interface ICaptureRouterDependencies {
idGenerator: IdGenerator<string>;
interactionPointerConverterFactory: (config: {
captureId: CaptureId;
captureBaseDirectory: string;
}) => IInteractionPointerConverter<LocalCaptureInteractionContext>;
fileReadBottleneck: Bottleneck;
}
export function makeRouter(dependencies: ICaptureRouterDependencies) {
const router = express.Router({ mergeParams: true });
router.put('/status', bodyParser.json({ limit: '1kb' }), async (req, res) => {
const { status } = req.body;
if (status !== 'completed') {
debugger;
return res.sendStatus(400);
}
try {
const { captureId } = req.params;
const captureInfo = await req.optic.capturesHelpers.loadCaptureState(
captureId
);
captureInfo.status = 'completed';
await req.optic.capturesHelpers.updateCaptureState(captureInfo);
res.sendStatus(204);
} catch (e) {
console.error(e);
debugger;
return res.sendStatus(400);
}
});
router.get('/status', async (req, res) => {
try {
const { captureId } = req.params;
const captureInfo = await req.optic.capturesHelpers.loadCaptureState(
captureId
);
const captureSummary = await req.optic.capturesHelpers.loadCaptureSummary(
captureId
);
res.json({
status: captureInfo.status,
diffsCount: captureSummary.diffsCount,
interactionsCount: captureSummary.interactionsCount,
});
} catch (e) {
return res.sendStatus(400);
}
});
////////////////////////////////////////////////////////////////////////////////
router.post(
'/initial-bodies',
bodyParser.json({ limit: '100mb' }),
async (req, res) => {
const { captureId } = req.params;
const { pathId, method, additionalCommands } = req.body;
const events = await req.optic.specLoader();
const newEventsString = opticEngine.try_apply_commands(
JSON.stringify(additionalCommands),
JSON.stringify(events),
'simulated-batch',
'simulated changes',
'simulated-client',
'simulated-session'
);
const initialBodyGenerator = new OnDemandInitialBodyRust({
captureBaseDirectory: req.optic.paths.capturesPath,
events: [...events, ...JSON.parse(newEventsString)],
captureId,
pathId,
method,
});
console.time('scheduling ' + pathId + method);
// TODO: pass results stream straight through instead of buffering into memory
const result = dependencies.fileReadBottleneck.schedule(() => {
console.timeEnd('scheduling ' + pathId + method);
console.time('executing learning ' + pathId + method);
return initialBodyGenerator.run();
});
result.then((learnedBodies: ILearnedBodies) => {
console.timeEnd('executing learning ' + pathId + method);
res.json(learnedBodies);
});
result.catch((e) => {
res.status(500).json({
message: e.message,
});
});
}
);
////////////////////////////////////////////////////////////////////////////////
router.post(
'/trail-values',
bodyParser.json({ limit: '100mb' }),
async (req, res) => {
const { captureId } = req.params;
const { diffId } = req.body;
const events = await req.optic.specLoader();
const onDemandTrailValues = new OnDemandShapeDiffAffordancesRust({
captureBaseDirectory: req.optic.paths.capturesPath,
diffId,
events: events,
captureId,
});
const result = onDemandTrailValues.run();
result.then((shapeDiffAffordancesByFingerprint) => {
res.json(shapeDiffAffordancesByFingerprint);
});
result.catch((e) => {
res.status(500).json({
message: e.message,
});
});
}
);
////////////////////////////////////////////////////////////////////////////////
router.get('/interactions/:interactionPointer', async (req, res) => {
const { captureId, interactionPointer } = req.params;
const interactionPointerConverter = dependencies.interactionPointerConverterFactory(
{
captureBaseDirectory: req.optic.paths.capturesPath,
captureId,
}
);
const interaction = await interactionPointerConverter.fromPointer(
interactionPointer
);
res.json({
interaction,
});
});
////////////////////////////////////////////////////////////////////////////////
return router;
}
|
tony-aq/optic
|
workspaces/spectacle/test/openapi/index.ts
|
<gh_stars>100-1000
// @ts-ignore
import Tap from 'tap';
import { makeSpectacle } from '../../src';
import { loadEvents } from '../utils';
import { InMemoryOpticContextBuilder } from '../../src/in-memory';
import * as OpticEngine from '../../../optic-engine-wasm/build';
import { generateOpenApi } from '../../src/openapi';
const specs = [
{
name: 'generate OpenAPI 3.0.1',
file: './test/specs/mark-req-nested-field-optional.json',
},
{
name: 'handle contributions',
file: './test/specs/contributions.json',
},
];
specs.forEach(({ name, file }) => {
Tap.test(name, async (test) => {
const events = loadEvents(file);
const opticContext = await InMemoryOpticContextBuilder.fromEvents(
OpticEngine,
events
);
const spectacle = await makeSpectacle(opticContext);
const results = await generateOpenApi(spectacle);
test.matchSnapshot(results);
});
});
|
tony-aq/optic
|
workspaces/optic-domain/tests/streams/spec-events.ts
|
import Tap from 'tap';
import * as AT from '../../src/async-tools';
import { SpecEvents } from '../../src/streams';
Tap.test('SpecEvents.takeUntilBatch', async (test) => {
await test.test('takes events until a batch commit id', async (t) => {
const exampleEvents = createExampleEvents();
const batchesUntil = SpecEvents.takeBatchesUntil(
'254b7e9e-053c-45f7-b18f-8a78782de2aa'
)(AT.from(exampleEvents));
const results = await AT.toArray<any>(batchesUntil);
test.matchSnapshot(results);
});
});
function createExampleEvents() {
return [
{
BatchCommitStarted: {
batchId: '254b7e9e-053c-45f7-b18f-8a78782de2aa',
commitMessage: 'Initialize specification attributes',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'unknown-session',
clientCommandBatchId: '254b7e9e-053c-45f7-b18f-8a78782de2aa',
createdAt: '2021-06-18T11:50:47.649234-07:00',
},
parentId: 'root',
},
},
{
ContributionAdded: {
id: 'metadata',
key: 'id',
value: 'a18156d3-f477-4c6e-a110-f7f91340772d',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'unknown-session',
clientCommandBatchId: '254b7e9e-053c-45f7-b18f-8a78782de2aa',
createdAt: '2021-06-18T11:50:47.649234-07:00',
},
},
},
{
BatchCommitEnded: {
batchId: '254b7e9e-053c-45f7-b18f-8a78782de2aa',
eventContext: {
clientId: 'anonymous',
clientSessionId: 'unknown-session',
clientCommandBatchId: '254b7e9e-053c-45f7-b18f-8a78782de2aa',
createdAt: '2021-06-18T11:50:47.649234-07:00',
},
},
},
{
BatchCommitStarted: {
batchId: 'c357b18e-657b-49c8-a430-5e992adc1824',
commitMessage: '1',
eventContext: {
clientId: 'anonymous',
clientSessionId: '9f6e6ba9-a3ac-4a91-a44c-8748f45be5b1',
clientCommandBatchId: 'c357b18e-657b-49c8-a430-5e992adc1824',
createdAt: '2021-06-18T11:50:53.353813-07:00',
},
parentId: '254b7e9e-053c-45f7-b18f-8a78782de2aa',
},
},
{
RequestAdded: {
requestId: 'request_TukeTP2v7j',
pathId: 'root',
httpMethod: 'GET',
eventContext: {
clientId: 'anonymous',
clientSessionId: '9f6e6ba9-a3ac-4a91-a44c-8748f45be5b1',
clientCommandBatchId: 'c357b18e-657b-49c8-a430-5e992adc1824',
createdAt: '2021-06-18T11:50:53.353813-07:00',
},
},
},
{
BatchCommitEnded: {
batchId: 'c357b18e-657b-49c8-a430-5e992adc1824',
eventContext: {
clientId: 'anonymous',
clientSessionId: '9f6e6ba9-a3ac-4a91-a44c-8748f45be5b1',
clientCommandBatchId: 'c357b18e-657b-49c8-a430-5e992adc1824',
createdAt: '2021-06-18T11:50:53.353813-07:00',
},
},
},
];
}
|
tony-aq/optic
|
workspaces/changelog/test/index.ts
|
import * as fs from 'fs';
import Tap from 'tap';
import { generateEndpointChanges } from '../src';
function loadSpecs(scenario: string) {
return {
initialSpec: JSON.parse(
fs.readFileSync(`./test/specs/${scenario}/initial.json`).toString(),
),
newSpec: JSON.parse(
fs.readFileSync(`./test/specs/${scenario}/new.json`).toString(),
),
};
}
const scenarios = fs
.readdirSync('./test/specs', { withFileTypes: true })
.filter((item) => item.isDirectory())
.map((item) => item.name);
scenarios.forEach((scenario) => {
Tap.test(`Check ${scenario} scenario`, async (test) => {
const { initialSpec, newSpec } = loadSpecs(scenario);
const result = await generateEndpointChanges(initialSpec, newSpec);
test.matchSnapshot(result);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.