Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

no tree branch isolation, run splitting on the whole tree #36

Merged
merged 7 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ This project is in the early stages of development. We are actively working on t

- [x] Limited support for NodeJS/Typescript
- [x] Simple UI
- [ ] Full support for NodeJS/Typescript
- [x] Full support for NodeJS/Typescript
- [ ] Python support with Flask
- [ ] Django support
- [ ] Full python support
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/components/MethodBadge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export default function MethodBadge(props: { method: string }) {
const [color, setColor] = useState<BadgeProps["color"]>("gray");

useEffect(() => {
switch (props.method.toLocaleLowerCase()) {
switch (props.method.toLowerCase()) {
case "get":
setColor("green");
break;
Expand Down
3 changes: 3 additions & 0 deletions packages/cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## [Unreleased]

Remove support for require and dynamic import
Code splitting now works take into account the whole dependencies. This fixes https://github.com/nanoapi-io/napi/issues/26

## [0.0.17] - 2024-11-01

Use indexes when editing file instead of search/replace
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
}
},
"scripts": {
"dev": "NODE_ENV=development ts-node src/index.ts",
"dev": "NODE_ENV=development nodemon src/index.ts",
"build": "tsc",
"start": "node dist/index.js",
"test": "vitest",
Expand Down
31 changes: 15 additions & 16 deletions packages/cli/src/api/split.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,38 @@ import { z } from "zod";
import { GroupMap } from "../helper/types";

export function split(payload: z.infer<typeof splitSchema>) {
let groupIndex = 0;
console.time("split command");
const groupMap: GroupMap = {};

// Get the dependency tree
const tree = getDependencyTree(payload.entrypointPath);

payload.outputDir = payload.outputDir || path.dirname(payload.entrypointPath);
const outputDir = payload.outputDir || path.dirname(payload.entrypointPath);

// Clean up and prepare the output directory
cleanupOutputDir(payload.outputDir);
createOutputDir(payload.outputDir);
cleanupOutputDir(outputDir);
createOutputDir(outputDir);

// Iterate over the tree and get endpoints
const endpoints = getEndpontsFromTree(tree);

// Get groups from the endpoints
const groups = getGroupsFromEndpoints(endpoints);

// Process each endpoint for splitting
for (const group of groups) {
createSplit(
group,
payload.outputDir,
payload.entrypointPath,
groupMap,
groupIndex,
);
groupIndex++;
}
// Process each group for splitting
groups.forEach((group, index) => {
// Clone the tree to avoid mutation of the original tree
const treeClone = structuredClone(tree);
createSplit(treeClone, group, outputDir, payload.entrypointPath, index);
});

// Store the processed annotations in the output directory
const annotationFilePath = path.join(payload.outputDir, "annotations.json");
groups.forEach((group, index) => {
groupMap[index] = group;
});
const annotationFilePath = path.join(outputDir, "annotations.json");
fs.writeFileSync(annotationFilePath, JSON.stringify(groupMap, null, 2));

console.timeEnd("split command");
return { groups, success: true };
}
59 changes: 30 additions & 29 deletions packages/cli/src/api/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { z } from "zod";
import { syncSchema } from "./helpers/validation";
import fs from "fs";
import {
getNanoApiAnnotationFromCommentValue,
replaceCommentFromAnnotation,
parseNanoApiAnnotation,
updateCommentFromAnnotation,
} from "../helper/annotations";
import {
getDependencyTree,
Expand All @@ -12,6 +12,8 @@ import {
import Parser from "tree-sitter";
import { getParserLanguageFromFile } from "../helper/treeSitter";
import { replaceIndexesFromSourceCode } from "../helper/cleanup";
import { getJavascriptAnnotationNodes } from "../helper/languages/javascript/annotations";
import { getTypescriptAnnotationNodes } from "../helper/languages/typescript/annotations";

export function sync(payload: z.infer<typeof syncSchema>) {
const tree = getDependencyTree(payload.entrypointPath);
Expand Down Expand Up @@ -48,35 +50,34 @@ export function sync(payload: z.infer<typeof syncSchema>) {
text: string;
}[] = [];

function traverse(node: Parser.SyntaxNode) {
if (node.type === "comment") {
const comment = node.text;

const annotation = getNanoApiAnnotationFromCommentValue(comment);

if (annotation) {
if (
annotation.path === endpoint.path &&
annotation.method === endpoint.method
) {
annotation.group = endpoint.group;
const updatedComment = replaceCommentFromAnnotation(
comment,
annotation,
);

indexesToReplace.push({
startIndex: node.startIndex,
endIndex: node.endIndex,
text: updatedComment,
});
}
}
}
node.children.forEach((child) => traverse(child));
let annotationNodes: Parser.SyntaxNode[];
if (language.name === "javascript") {
annotationNodes = getJavascriptAnnotationNodes(parser, tree.rootNode);
} else if (language.name === "typescript") {
annotationNodes = getTypescriptAnnotationNodes(parser, tree.rootNode);
} else {
throw new Error("Language not supported");
}

traverse(tree.rootNode);
annotationNodes.forEach((node) => {
const annotation = parseNanoApiAnnotation(node.text);
if (
annotation.path === endpoint.path &&
annotation.method === endpoint.method
) {
annotation.group = endpoint.group;
const updatedComment = updateCommentFromAnnotation(
node.text,
annotation,
);

indexesToReplace.push({
startIndex: node.startIndex,
endIndex: node.endIndex,
text: updatedComment,
});
}
});

sourceCode = replaceIndexesFromSourceCode(sourceCode, indexesToReplace);

Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/split.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ export default function splitCommandHandler(
entrypointPath: string, // Path to the entrypoint file
outputDir: string, // Path to the output directory
) {
let groupIndex = 0;
const groupMap: GroupMap = {};

const tree = getDependencyTree(entrypointPath);
Expand All @@ -27,13 +26,17 @@ export default function splitCommandHandler(
// Get groups from the endpoints
const groups = getGroupsFromEndpoints(endpoints);

// Process each endpoint for splitting
for (const group of groups) {
createSplit(group, outputDir, entrypointPath, groupMap, groupIndex);
groupIndex++;
}
// Process each group for splitting
groups.forEach((group, index) => {
// Clone the tree to avoid mutation of the original tree
const treeClone = structuredClone(tree);
createSplit(treeClone, group, outputDir, entrypointPath, index);
});

// Store the processed annotations in the output directory
groups.forEach((group, index) => {
groupMap[index] = group;
});
const annotationFilePath = path.join(outputDir, "annotations.json");
fs.writeFileSync(annotationFilePath, JSON.stringify(groupMap, null, 2));
}
41 changes: 36 additions & 5 deletions packages/cli/src/helper/annotations.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { NanoAPIAnnotation } from "./types";
import { Group, NanoAPIAnnotation } from "./types";

export function getNanoApiAnnotationFromCommentValue(comment: string) {
export function parseNanoApiAnnotation(value: string) {
const nanoapiRegex = /@nanoapi|((method|path|group):([^ ]+))/g;
const matches = comment.match(nanoapiRegex);
const matches = value.match(nanoapiRegex);
// remove first match, which is the @nanoapi identifier
matches?.shift();

Expand All @@ -16,10 +16,41 @@ export function getNanoApiAnnotationFromCommentValue(comment: string) {
}, {} as NanoAPIAnnotation);
}

return null;
throw new Error("Could not parse annotation");
}

export function replaceCommentFromAnnotation(
export function isAnnotationInGroup(
group: Group,
annotation: NanoAPIAnnotation,
) {
// check if annotation has a method (actual endpoint)
if (annotation.method) {
const endpoint = group.endpoints.find(
(endpoint) =>
endpoint.method === annotation.method &&
endpoint.path === annotation.path,
);

if (endpoint) {
return true;
}

return false;
}

// if annotation has no method, we treat it as a module that contains other endpoints
const endpoints = group.endpoints.filter((endpoint) =>
endpoint.path.startsWith(annotation.path),
);

if (endpoints.length > 0) {
return true;
}

return false;
}

export function updateCommentFromAnnotation(
comment: string,
annotation: NanoAPIAnnotation,
) {
Expand Down
Loading
Loading