`,
263 | 401,
264 | "text/html",
265 | );
266 | return;
267 | }
268 | } else {
269 | ctx.send(UI, 200, "text/html");
270 | return;
271 | }
272 | });
273 | }
274 | }
275 |
276 | //? exports
277 | export type {
278 | JetContext,
279 | JetFile,
280 | JetMiddleware,
281 | JetRoute,
282 | JetPluginExecutorInitParams
283 | } from "./primitives/types.js";
284 | export { JetServer } from "./primitives/classes.js";
285 | export { use } from "./primitives/functions.js";
286 | export { mime } from "./extracts/mimejs-extract.js";
287 |
--------------------------------------------------------------------------------
/example/routes/reviews.jet.ts:
--------------------------------------------------------------------------------
1 | // src/routes/reviews.ts
2 |
3 | import { type JetRoute, use } from "../../dist/index.js";
4 | // Import AuthPluginType if authentication checks are done within route handlers
5 | import { type AuthPluginType } from "../plugins/auth.ts";
6 | // Import data models and in-memory data arrays
7 | import { pets, reviews } from "../data/models.ts";
8 | import { type ReviewType } from "../types.ts"; // Import ReviewType
9 |
10 | // --- Reviews Management Routes ---
11 |
12 | /**
13 | * Get all reviews for a pet
14 | * @route GET /petBy/:id/reviews
15 | * @access Public
16 | * Demonstrates: Dynamic GET route ($id), path parameter, filtering related data, sorting, calculating aggregates (average rating).
17 | */
18 | export const GET_petBy$id_reviews: JetRoute<{
19 | params: { id: string }; // Pet ID from path
20 | query: { sort?: string }; // Optional sort query parameter
21 | }> = function (ctx) {
22 | const petId = ctx.params.id; // Access pet ID from path.
23 | const sort = ctx.parseQuery().sort || "-createdAt"; // Access sort query param, default to newest first.
24 |
25 | // Find the pet to ensure it exists.
26 | const pet = pets.find((p) => p.id === petId);
27 |
28 | if (!pet) {
29 | ctx.code = 404; // Not Found
30 | ctx.send({
31 | status: "error",
32 | message: `Pet with ID ${petId} not found.`,
33 | });
34 | return;
35 | }
36 |
37 | // Filter reviews to get only those for the specified pet.
38 | let petReviews = reviews.filter((review) => review.petId === petId);
39 |
40 | // Sort the filtered reviews based on the sort query parameter.
41 | const sortField = sort.startsWith("-") ? sort.substring(1) : sort; // Get field name (remove leading '-')
42 | const sortDirection = sort.startsWith("-") ? -1 : 1; // Determine sort direction (1 for asc, -1 for desc)
43 |
44 | // Sort the array. Using `any` for simplicity due to dynamic sortField access.
45 | petReviews.sort((a: any, b: any) => {
46 | const valueA = a[sortField];
47 | const valueB = b[sortField];
48 |
49 | if (valueA < valueB) return -1 * sortDirection;
50 | if (valueA > valueB) return 1 * sortDirection;
51 | return 0; // Values are equal
52 | });
53 |
54 | // Calculate aggregate statistics for the reviews (e.g., average rating).
55 | const totalRating = petReviews.reduce(
56 | (sum, review) => sum + review.rating,
57 | 0,
58 | ); // Sum of all ratings
59 | const averageRating = petReviews.length > 0
60 | ? totalRating / petReviews.length
61 | : 0; // Calculate average, handle division by zero.
62 |
63 | // Send the response with the filtered, sorted reviews and statistics.
64 | ctx.send({
65 | status: "success",
66 | petId: petId,
67 | petName: pet.name,
68 | stats: { // Include review statistics
69 | count: petReviews.length,
70 | averageRating: averageRating,
71 | },
72 | reviews: petReviews, // Include the list of reviews
73 | });
74 | };
75 |
76 | // Apply .info() for documentation.
77 | use(GET_petBy$id_reviews).title("Get all reviews for a specific pet").query(
78 | (t) => {
79 | // Define the expected query parameters and validation rules.
80 | return {
81 | // Optional sort parameter, default to '-createdAt' (newest first).
82 | sort: t.string({
83 | err: "Sort parameter must be a string",
84 | }).default("-createdAt"),
85 | };
86 | },
87 | );
88 |
89 | /**
90 | * Add a review for a pet
91 | * @route POST /petBy/:id/reviews
92 | * @access Authenticated (Based on sample's middleware check)
93 | * Demonstrates: POST request, dynamic routing ($id), body parsing, input validation (use().body()), data insertion.
94 | */
95 | export const POST_petBy$id_reviews: JetRoute<{
96 | params: { id: string }; // Pet ID from path
97 | body: { // Expected request body structure
98 | rating: number;
99 | comment: string;
100 | };
101 | }, [AuthPluginType]> = async function (ctx) {
102 | // Check if user is authenticated (access user and authenticated status from ctx.state/plugins)
103 | // The global middleware sets ctx.state.user if authenticated.
104 | const user = ctx.state["user"];
105 | if (!user) {
106 | ctx.code = 401; // Unauthorized
107 | ctx.send({
108 | status: "error",
109 | message: "Authentication required to post reviews",
110 | });
111 | return;
112 | }
113 |
114 | const petId = ctx.params.id; // Access pet ID from path.
115 |
116 | // Find the pet to ensure it exists before adding a review.
117 | const pet = pets.find((p) => p.id === petId);
118 |
119 | if (!pet) {
120 | ctx.code = 404; // Not Found
121 | ctx.send({
122 | status: "error",
123 | message: `Pet with ID ${petId} not found.`,
124 | });
125 | return;
126 | }
127 |
128 | // Parse and validate the request body. Jetpath handles this via use().body().
129 | const { rating, comment } = await ctx.parse(); // Ensure body is parsed
130 |
131 | // Create a new review object with a unique ID and current timestamp.
132 | const newReview: ReviewType = {
133 | id: `review-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`, // Generate unique ID
134 | petId: petId, // Link to the pet
135 | userId: user.id, // Link to the authenticated user's ID
136 | username: user.username, // Store the reviewer's username
137 | rating: rating, // Rating from the request body
138 | comment: comment, // Comment from the request body
139 | createdAt: new Date().toISOString(), // Set creation timestamp
140 | };
141 |
142 | // Add the new review to the in-memory database array.
143 | reviews.push(newReview);
144 |
145 | // Log the review creation action.
146 | // Log the review creation action.
147 | ctx.plugins?.["info"]({
148 | action: "create_review",
149 | reviewId: newReview.id,
150 | petId: newReview.petId,
151 | userId: newReview.userId,
152 | message: `User ${newReview.username} added review for pet ${pet.name}`,
153 | });
154 |
155 | // Send a 201 Created response with the newly created review details.
156 | ctx.code = 201; // Created status code.
157 | ctx.send({
158 | status: "success",
159 | message: "Review added successfully",
160 | review: newReview,
161 | });
162 | };
163 |
164 | // Apply body validation and .info() for documentation using use() chained after the function definition.
165 | use(POST_petBy$id_reviews).body((t) => {
166 | // Define the expected request body structure and validation rules.
167 | return {
168 | // Validate rating as a required number.
169 | rating: t.number({
170 | err: "Rating is required (1-5)",
171 | }).required(),
172 | // Validate comment as a required string.
173 | comment: t.string({ err: "Review comment is required" }).required(),
174 | };
175 | }).title("Add a review for a specific pet (authenticated users only)");
176 |
177 | /**
178 | * Delete a review
179 | * @route DELETE /reviews/:reviewId
180 | * @access Authenticated (Review owner or Admin - Based on sample logic)
181 | * Demonstrates: DELETE request, dynamic routing ($reviewId), path parameter, data deletion, authorization check (owner or admin).
182 | */
183 | export const DELETE_reviews$reviewId: JetRoute<{
184 | params: { reviewId: string }; // Review ID from path
185 | }, [AuthPluginType]> = function (ctx) {
186 | // Check if user is authenticated.
187 | const user = ctx.state["user"];
188 | if (!user) {
189 | ctx.code = 401; // Unauthorized
190 | ctx.send({
191 | status: "error",
192 | message: "Authentication required to delete reviews",
193 | });
194 | return;
195 | }
196 |
197 | const reviewId = ctx.params.reviewId; // Access review ID from path.
198 |
199 | // Find index of the review by ID.
200 | const reviewIndex = reviews.findIndex((r) => r.id === reviewId);
201 |
202 | // If review is not found, set 404 status and send error response.
203 | if (reviewIndex === -1) {
204 | ctx.code = 404; // Not Found
205 | ctx.send({
206 | status: "error",
207 | message: `Review with ID ${reviewId} not found.`,
208 | });
209 | return;
210 | }
211 |
212 | const review = reviews[reviewIndex]; // Get the review object.
213 |
214 | // Authorization Check: Check if the authenticated user is the owner of the review OR an admin.
215 | const isOwner = review.userId === user.id;
216 | const isAdmin = user.role === "admin";
217 |
218 | if (!isOwner && !isAdmin) {
219 | ctx.code = 403; // Forbidden
220 | ctx.send({
221 | status: "error",
222 | message: "You don't have permission to delete this review",
223 | });
224 | return;
225 | }
226 |
227 | // Remove the review from the in-memory array using splice().
228 | const deletedReview = reviews.splice(reviewIndex, 1)[0];
229 |
230 | // Log the deletion action.
231 | ctx.plugins?.["info"]({
232 | action: "delete_review",
233 | reviewId: deletedReview.id,
234 | petId: deletedReview.petId,
235 | userId: user.id,
236 | message: `User ${user.username} deleted review ${deletedReview.id}`,
237 | });
238 |
239 | // Send a success response with details of the deleted review.
240 | ctx.send({
241 | status: "success",
242 | message: `Review with ID ${reviewId} deleted successfully`,
243 | review: deletedReview,
244 | });
245 | };
246 |
247 | // Apply .info() for documentation.
248 | use(DELETE_reviews$reviewId).title(
249 | "Delete a review (admin or review owner only)",
250 | );
251 |
252 | // Export route handlers so Jetpath can discover and register them based on naming convention.
253 |
--------------------------------------------------------------------------------
/contributing.md:
--------------------------------------------------------------------------------
1 |
2 | # JetPath Contributing Guide
3 |
4 |
5 | Welcome to the JetPath Contributing Guide, and thank you for your interest.
6 |
7 | If you would like to contribute to a specific part of the project, check out the following list of contributions that we accept and their corresponding sections that are within this guide:
8 |
9 | * Documentation
10 | * Go to the `docs` dir
11 | * Bug Fixes
12 | * Go to source code dir at `src`
13 | * New Features
14 | * Create a sample of the new feature, and start a discussion in the community forum.
15 |
16 | However, at this time, we do not accept the following contributions:
17 |
18 | * Maintenance
19 |
20 | ## JetPath overview
21 |
22 | The purpose of the JetPath is to streamline your development process while offering flexibility in your choice of runtime environment
23 |
24 | ## Ground rules
25 |
26 | Before contributing, read our [Code of Conduct](https://github.com/CodeDynasty-dev/Jetpath?tab=coc-ov-file) to learn more about our community guidelines and expectations.
27 |
28 | ## Community engagement
29 |
30 | Refer to the following channels to connect with fellow contributors or to stay up-to-date with news about JetPath:
31 |
32 | * Join our project contributors on {name and link to online chat}.Discord
33 | * Participate in our project meetings on {specify the day of the week and cadence} at {specify time and timezone}, where you can provide a status update or raise questions and concerns about your contributions. Use the following link to join: {link to online meeting space}
34 | 2-3 meetings monthly, Fridays
35 |
36 | ## Before you start
37 |
38 | Before you start contributing, ensure you have the following:
39 | * For developers: The latest version of [Node.js](https://nodejs.org/en/download), [Bon.js](https://bun.sh/), [Deno.js](https://deno.com/).
40 | * For writers: The lastest version of [Node.js](https://nodejs.org/en/download).
41 |
42 |
43 | ## Environment setup
44 |
45 | To set up your environment, perform the following actions:
46 |
47 | ### Developer
48 |
49 | 1. Fork the Repository: Click the **Fork** button at the top right of the repository page to create a copy under your GitHub account.
50 |
51 | 2. Clone your forked repository to your computer using the command below. Replace `yourusername` with your GitHub username:
52 |
53 | ```bash
54 | git clone https://github.com//JetPath.git
55 | ```
56 | 3. Navigate to the Project Directory: Change into the project folder using the command below.
57 |
58 | ```bash
59 | cd JetPath
60 | ```
61 | 4. Install Dependencies: Install all necessary packages with npm:
62 |
63 | ```bash
64 | npm install
65 |
66 | ```
67 | This will download and set up all libraries the project depends on.
68 |
69 | 5. Create a new branch for your feature or fix
70 | ```bash
71 | git checkout -b your-feature-branch
72 | ```
73 | 6. Run the Development Server: Start the local server to preview your changes
74 |
75 | ```bash
76 | npm run dev
77 | ```
78 | Open your browser and click the URL shown in the terminal (usually http://localhost:4000).
79 |
80 | 7. Compile the Project: Run the following command to build the project for production
81 |
82 | ```bash
83 | npm run compile
84 | ```
85 | 8. Push your branch to your fork and open a Pull Request to the main repository.
86 | Feel free to ask questions or open an issue if you need help!
87 |
88 |
89 | ### Writers
90 |
91 |
92 | 1. Fork the Repository: Click the **Fork** button at the top right of the repository page to create a copy under your GitHub account.
93 |
94 | 2. Clone your forked repository to your computer using the command below. Replace with your GitHub username:
95 |
96 | ```bash
97 | git clone https://github.com//JetPath.git
98 | ```
99 | 3. Navigate to the Project Directory: Change into the project folder using the command below.
100 |
101 | ```bash
102 | cd JetPath
103 | ```
104 | 4. Install Dependencies
105 | ```bash
106 | npm install
107 |
108 | ```
109 |
110 | 5. Create a new branch
111 |
112 | ```bash
113 | git checkout -b your-feature-branch
114 | ```
115 | 6. Preview your changes with this command below
116 |
117 | ```bash
118 | npx docmach
119 | ```
120 |
121 | 7. Push your branch to your fork and open a Pull Request to the main repository.
122 |
123 | Open your browser and click the URL shown in the terminal (usually http://localhost:4000).
124 |
125 |
126 |
127 | ### Troubleshoot
128 |
129 | If you encounter issues as you set up your environment,
130 | reach out to the team @fridaycandour for development and @NickyShe for documentation.
131 |
132 |
133 | ## Best practices
134 |
135 | Our project uses the [Google Typescript coding style guide](https://github.com/google/gts) as our parent guide for best practices. Reference the guide to familiarize yourself with the best practices we want contributors to follow
136 | ### Developers
137 |
138 | * Organize your code properly
139 | * Always run your test before pushing any code
140 |
141 | ### Writers
142 |
143 | Read the [Google developers documentation writing style guide](https://developers.google.com/style) to understand the guidelines for writing and formatting documents. The purpose of the style guide is to ensure consistency in the tone, voice, and structure of our documentation.
144 |
145 | ## Contribution workflow
146 |
147 | ### Report issues and bugs
148 |
149 | To help us improve JetPath, please report any issues or bugs you encounter. Here’s how you can do it:
150 |
151 | 1. **Check existing issues**: Before creating a new issue, search the issue tracker to see if someone else has already reported the problem.
152 | 2. **Create a new issue**: If you can’t find an existing issue, click the **New issue** button and fill out the template provided. Make sure to include:
153 | * Summarize the issue in a few words.
154 | * Explain the problem, including any error messages or unexpected behavior.
155 | * List the steps you took that led to the issue.
156 | * Describe what you expected to happen and what actually happened.
157 | * Attach any relevant screenshots or log files if applicable.
158 |
159 | 3. **Provide context**: If relevant, mention your environment for example, operating system, browser, version of JetPath.
160 |
161 | 4. **Use Labels**: Apply labels to categorize issues by type for eexample,bug, feature request, documentation.
162 | 5. **Prioritize**: Use priority labels for example, high, medium, low to indicate the urgency of the issue.
163 |
164 | 6. **Comment and discuss**: Use the issue comments to discuss the problem and potential solutions with other contributors.
165 |
166 | By following these steps, we can efficiently track and resolve issues, ensuring JetPath continues to improve for everyone.
167 |
168 | ### Commit messages
169 | Here are the types and description of commit messages
170 |
171 | | Type | Description |
172 | |----------|------------ |
173 | | feat | New feature |
174 | | fix | Bug fix |
175 | | docs | Documentation changes |
176 | | chore | Maintenance / build tasks |
177 | | refactor | Code refactoring without feature change |
178 |
179 | Example Commit message
180 |
181 | ```bash
182 | feat: add support for Deno.js runtime environment detection
183 |
184 | fix: resolve issue with npm run compile failing on Windows
185 |
186 | docs: update contributing guide with branch naming conventions
187 |
188 | chore: upgrade dependencies to latest stable versions
189 |
190 | refactor: reorganize src/utils for better modularity
191 |
192 | ```
193 |
194 | ### Branch creation
195 |
196 | To keep our repository organized and make collaboration easier, please follow these guidelines when creating and naming branches:
197 |
198 | Use a consistent prefix to indicate the type of work:
199 |
200 | * feature/ for new features
201 |
202 | * bugfix/ for bug fixes
203 |
204 | * hotfix/ for urgent or critical fixes
205 |
206 | * release/ for release preparation
207 |
208 | * docs/ for documentation updates
209 |
210 | Example:
211 | ```bash
212 | git checkout -b feature/add-user-authentication
213 | git checkout -b bugfix/fix-login-error
214 | git checkout -b docs/update-contributing-guide
215 | git checkout -b release/1.0.0
216 |
217 | ```
218 | Sticking to these conventions helps everyone quickly understand the purpose of each branch and keeps our workflow efficient
219 |
220 | ### Pull requests
221 |
222 | When your changes are ready, submit a pull request (PR) to propose merging your branch into the main repository. Please follow these steps:
223 |
224 | 1. Push your branch to your forked repository:
225 |
226 | ```bash
227 | git push -u origin your-branch-name
228 | ```
229 | 2. Open a pull request on GitHub:
230 |
231 | * Navigate to the main repository on GitHub.
232 |
233 | * Click "Compare & pull request" next to your branch.
234 |
235 | * Ensure the base branch is main (or the appropriate target branch).
236 |
237 | 3. Fill out the pull request template:
238 |
239 | * Provide a clear title and description.
240 |
241 | * List the main changes and the motivation behind them.
242 |
243 | * Reference any related issues by number (e.g., fixes #42).
244 |
245 | Pull Request Template Example:
246 | ```
247 | ## Description
248 | Briefly describe the purpose of this pull request.
249 |
250 | ## Changes
251 | - List key changes here
252 |
253 | ## Additional Information
254 | Add any extra context, screenshots, or testing instructions.
255 |
256 | ## Checklist
257 | - [ ] Tests passed
258 | - [ ] Documentation updated
259 | ```
260 |
261 | ### Releases
262 |
263 | {Provide a description of the release process and cadence for the project, such as the source code.}
264 |
265 |
266 | ---
267 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | Copyright 2023 friday candour
179 |
180 | Licensed under the Apache License, Version 2.0 (the "License");
181 | you may not use this file except in compliance with the License.
182 | You may obtain a copy of the License at
183 |
184 | http://www.apache.org/licenses/LICENSE-2.0
185 |
186 | Unless required by applicable law or agreed to in writing, software
187 | distributed under the License is distributed on an "AS IS" BASIS,
188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189 | See the License for the specific language governing permissions and
190 | limitations under the License.
191 |
--------------------------------------------------------------------------------
/src/primitives/types.ts:
--------------------------------------------------------------------------------
1 | import { IncomingMessage, Server, ServerResponse } from "node:http";
2 | import type { _JetPath_paths, v } from "./functions.js";
3 | import { type CookieOptions, SchemaBuilder } from "./classes.js";
4 | import type { BunFile } from "bun";
5 | import type Stream from "node:stream";
6 |
7 | export type UnionToIntersection =
8 | (U extends any ? (x: U) => void : never) extends (
9 | x: infer I,
10 | ) => void ? I
11 | : never;
12 |
13 | export interface JetContext<
14 | JetData extends {
15 | body?: Record;
16 | params?: Record;
17 | query?: Record;
18 | } = { body: {}; params: {}; query: {} },
19 | JetPluginTypes extends Record[] = [],
20 | > {
21 | /**
22 | * an object you can set values to per request
23 | */
24 | state: Record;
25 | /**
26 | * an object you can set values to per request
27 | */
28 | plugins: UnionToIntersection & Record;
29 | /**
30 | * get body params after /?
31 | */
32 | // body: Promise;
33 | /**
34 | * get query params after /?
35 | */
36 | // query: JetData["query"];
37 | /**
38 | * get route params in /:thing
39 | */
40 | params: JetData["params"];
41 | /**
42 | * websocket socket event class
43 | */
44 | connection: jet_socket;
45 | /**
46 | * reply the request
47 | */
48 | request: Request;
49 | /**
50 | * API status
51 | */
52 | code: number;
53 | /**
54 | * send a stream
55 | * @param stream - The stream or file path to send
56 | * @param folder - The folder to save the stream to
57 | * @param ContentType - The content type of the stream
58 | *
59 | * PLEASE PROVIDE A VALID FOLDER PATH FOR SECURITY REASONS
60 | */
61 | sendStream(
62 | stream: Stream | string | BunFile,
63 | config?: {
64 | folder?: string;
65 | ContentType?: string;
66 | },
67 | ): void | never;
68 | /**
69 | * send a file for download
70 | * @param stream - The file path to send
71 | * @param folder - The folder to save the stream to
72 | * @param ContentType - The content type of the stream
73 | *
74 | * PLEASE PROVIDE A VALID FOLDER PATH FOR SECURITY REASONS
75 | */
76 | download(
77 | stream: string | BunFile,
78 | config?: {
79 | folder?: string;
80 | ContentType?: string;
81 | },
82 | ): void;
83 | /**
84 | * send a direct response
85 | * *Only for deno and bun
86 | */
87 | sendResponse(response?: Response): void;
88 | /**
89 | * reply the request
90 | */
91 | send(data: unknown, statusCode?: number, ContentType?: string): void;
92 | /**
93 | * redirect the request
94 | */
95 | redirect(url: string): void;
96 | /**
97 | * get request header values
98 | */
99 | get(field: string): string | undefined;
100 | /**
101 | * set request header values
102 | */
103 | set(field: string, value: string): void;
104 | /**
105 | * Parses the request body
106 | */
107 | getCookie(name: string): string | undefined;
108 | getCookies(): Record;
109 | setCookie(name: string, value: string, options: CookieOptions): void;
110 | clearCookie(name: string, options: CookieOptions): void;
111 | parse(options?: {
112 | maxBodySize?: number;
113 | contentType?: string;
114 | }): Promise;
115 | parseQuery(): JetData["query"];
116 | /**
117 | * Upgrade the request to a WebSocket connection
118 | */
119 | upgrade(): void | never;
120 | /**
121 | * get original request
122 | */
123 | path: string;
124 | payload?: string;
125 | _2?: Record;
126 | _3?: any; //Stream | undefined; // Stream
127 | _4?: boolean | undefined;
128 | _5?: JetRoute | undefined;
129 | _6?: Response | false;
130 | }
131 |
132 | export type JetPluginExecutorInitParams = {
133 | runtime: {
134 | node: boolean;
135 | bun: boolean;
136 | deno: boolean;
137 | };
138 | server: Server;
139 | routesObject: typeof _JetPath_paths;
140 | JetPath_app: (req: Request) => Response;
141 | };
142 |
143 | export type contentType =
144 | | "application/x-www-form-urlencoded"
145 | | "multipart/form-data"
146 | | "application/json";
147 |
148 | export type methods =
149 | | "GET"
150 | | "POST"
151 | | "OPTIONS"
152 | | "DELETE"
153 | | "HEAD"
154 | | "PUT"
155 | | "CONNECT"
156 | | "TRACE"
157 | | "PATCH";
158 |
159 | export type allowedMethods = methods[];
160 |
161 | export type jetOptions = {
162 | /**
163 | * edge grabber helps capture defined API functions in an edge environment
164 | * and avoids fs system scanning.
165 | * @example
166 | * ```ts
167 | * edgeGrabber: [
168 | * GET_api_users,
169 | * POST_api_users,
170 | * Middleware_api_users,
171 | * ]
172 | * ```
173 | */
174 | edgeGrabber?: JetRoute[] & JetMiddleware[];
175 | /**
176 | * upgrade the request to a WebSocket connection
177 | */
178 | upgrade?: boolean;
179 | /**
180 | * source of the app
181 | */
182 | source?: string;
183 | /**
184 | * global headers
185 | */
186 | globalHeaders?: Record;
187 | /**
188 | * strict mode
189 | */
190 | strictMode?: "ON" | "OFF" | "WARN";
191 | /**
192 | * generated routes file path
193 | * putting the file on the frontend folder will make it accessible
194 | * during build time
195 | * @default generates nothing
196 | */
197 | generatedRoutesFilePath?: string;
198 | /**
199 | * keep alive timeout
200 | */
201 | keepAliveTimeout?: number;
202 | /**
203 | * api documentation options
204 | */
205 | apiDoc?: {
206 | display?: "UI" | "HTTP" | false;
207 | environments?: Record;
208 | name?: string;
209 | info?: string;
210 | color?: string;
211 | logo?: string;
212 | path?: string;
213 | password?: string;
214 | username?: string;
215 | };
216 | /**
217 | * credentials options
218 | */
219 | credentials?: {
220 | cert: string;
221 | key: string;
222 | };
223 | /**
224 | * port
225 | */
226 | port?: number;
227 | /**
228 | * cors options
229 | */
230 | cors?:
231 | | {
232 | allowMethods?: allowedMethods;
233 | secureContext?: {
234 | "Cross-Origin-Opener-Policy":
235 | | "same-origin"
236 | | "unsafe-none"
237 | | "same-origin-allow-popups";
238 | "Cross-Origin-Embedder-Policy": "require-corp" | "unsafe-none";
239 | };
240 | allowHeaders?: string[];
241 | exposeHeaders?: string[];
242 | keepHeadersOnError?: boolean;
243 | maxAge?: string;
244 | credentials?: boolean;
245 | privateNetworkAccess?: any;
246 | origin?: string[];
247 | }
248 | | boolean;
249 | };
250 |
251 | export type HTTPBody> = {
252 | [x in keyof Obj]: {
253 | err?: string;
254 | type?:
255 | | "string"
256 | | "number"
257 | | "file"
258 | | "object"
259 | | "boolean"
260 | | "array"
261 | | "date";
262 | arrayType?:
263 | | "string"
264 | | "number"
265 | | "file"
266 | | "object"
267 | | "boolean"
268 | | "array"
269 | | "date";
270 | RegExp?: RegExp;
271 | inputAccept?: string;
272 | inputType?:
273 | | "date"
274 | | "email"
275 | | "file"
276 | | "password"
277 | | "number"
278 | | "time"
279 | | "tel"
280 | | "datetime"
281 | | "url";
282 | inputDefaultValue?: string | number | boolean;
283 | required?: boolean;
284 | validator?: (value: any) => boolean | string;
285 | objectSchema?: HTTPBody>;
286 | };
287 | };
288 |
289 | export type Middleware<
290 | JetData extends {
291 | body?: Record;
292 | params?: Record;
293 | query?: Record;
294 | } = { body: {}; params: {}; query: {} },
295 | JetPluginTypes extends Record[] = [],
296 | > = (
297 | ctx: JetContext,
298 | ) =>
299 | | void
300 | | Promise
301 | | ((
302 | ctx: JetContext,
303 | error: unknown,
304 | ) => void | Promise)
305 | | Promise<
306 | ((
307 | ctx: JetContext,
308 | error: unknown,
309 | ) => void | Promise) | undefined
310 | >
311 | | undefined;
312 |
313 | export type JetMiddleware<
314 | JetData extends {
315 | body?: Record;
316 | params?: Record;
317 | query?: Record;
318 | } = { body: {}; params: {}; query: {} },
319 | JetPluginTypes extends Record[] = [],
320 | > = Middleware | Middleware[];
321 |
322 | export type JetRoute<
323 | JetData extends {
324 | body?: Record;
325 | params?: Record;
326 | query?: Record;
327 | response?: Record;
328 | } = {
329 | body: {};
330 | params: {};
331 | query: {};
332 | response: {};
333 | title: "";
334 | description: "";
335 | method: "";
336 | path: "";
337 | jet_middleware: [];
338 | },
339 | JetPluginTypes extends Record[] = [],
340 | > = {
341 | (ctx: JetContext): Promise | void;
342 | body?: HTTPBody>;
343 | headers?: Record;
344 | title?: string;
345 | description?: string;
346 | method?: string;
347 | path?: string;
348 | jet_middleware?: Middleware[];
349 | params?: HTTPBody>;
350 | query?: HTTPBody>;
351 | response?: HTTPBody>;
352 | };
353 |
354 | interface jet_socket {
355 | addEventListener(
356 | event: "message" | "close" | "drain" | "open",
357 | listener: (socket: WebSocket, ...params: any[]) => void,
358 | ): void;
359 | }
360 |
361 | export type JetFile = {
362 | fileName: string;
363 | content: Uint8Array;
364 | mimeType: string;
365 | };
366 |
367 | export type SchemaType =
368 | | "string"
369 | | "number"
370 | | "boolean"
371 | | "array"
372 | | "object"
373 | | "date"
374 | | "file";
375 |
376 | export interface ValidationOptions {
377 | err?: string;
378 | RegExp?: RegExp;
379 | validator?: (value: any) => boolean | string;
380 | inputDefaultValue?: any;
381 | required?: boolean;
382 | }
383 | export interface FileOptions {
384 | inputAccept?: string;
385 | inputMultiple?: boolean;
386 | err?: string;
387 | }
388 |
389 | export interface ArrayOptions extends ValidationOptions {
390 | arrayType?: SchemaType | "object";
391 | objectSchema?: HTTPBody;
392 | }
393 |
394 | export interface ObjectOptions extends ValidationOptions {
395 | objectSchema?: HTTPBody;
396 | }
397 |
398 | export type SchemaDefinition =
399 | & {
400 | type: SchemaType;
401 | }
402 | & ValidationOptions
403 | & ArrayOptions
404 | & ObjectOptions;
405 |
406 | export type compilerType<
407 | JetData extends {
408 | body?: Record;
409 | params?: Record;
410 | query?: Record;
411 | response?: Record;
412 | },
413 | JetPluginTypes extends Record[] = [],
414 | > = {
415 | //? docs and validation
416 | /**
417 | * Sets the API body validation and documentation body for the endpoint
418 | */
419 | body: (
420 | schemaFn: (
421 | t: typeof v,
422 | ) => Partial<
423 | Record>, SchemaBuilder>
424 | >,
425 | ) => compilerType;
426 | /**
427 | * Sets the API body validation and documentation body for the endpoint
428 | */
429 | response: (
430 | schemaFn: (
431 | t: typeof v,
432 | ) => Partial<
433 | Record>, SchemaBuilder>
434 | >,
435 | ) => compilerType;
436 | //? docs and validation
437 | /**
438 | * Sets the API documentation query for the endpoint
439 | */
440 | query: (
441 | schemaFn: (
442 | t: typeof v,
443 | ) => Partial<
444 | Record>, SchemaBuilder>
445 | >,
446 | ) => compilerType;
447 |
448 | //? docs only
449 | /**
450 | * Sets the API documentation title for the endpoint
451 | */
452 | title: (title: string) => compilerType;
453 | //? docs only
454 | /**
455 | * Sets the API documentation description for the endpoint
456 | */
457 | description: (description: string) => compilerType;
458 | };
459 |
--------------------------------------------------------------------------------
/src/assets/api-doc.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | {NAME} API
8 |
9 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
{NAME} API Documentation
421 |
422 |
423 |
424 |
425 |
426 |
Project Information
427 |
{INFO}
428 |
Project Global Headers
429 |
430 |
431 |
432 |
433 |
434 |
435 |
API Endpoints
436 |
437 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
450 |
451 |
452 |
453 |
456 |
457 |
458 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 |
2 | # PetShop API Sample
3 |
4 | The goal is to make the codebase clearer for beginners by splitting the original monolithic file into logical modules, while preserving all the features and conventions demonstrated in the original sample.
5 |
6 | This structure helps beginners understand how to build a Jetpath application by separating concerns into different files:
7 |
8 | - **Framework Initialization and Configuration:** How the app is set up.
9 | - **Global Middleware:** Logic applied to all requests (logging, error handling).
10 | - **Data Models and Storage:** Where data structures and in-memory data reside.
11 | - **API Routes:** Grouping related API endpoints together.
12 | - **Utilities/Miscellaneous Routes:** Other supporting endpoints.
13 | - **WebSockets:** Handling real-time communication.
14 | - **Plugins:** External functionalities integrated into the framework.
15 |
16 | All features from the original `app.jet.ts` sample are included in this version, including:
17 |
18 | - Convention-over-configuration routing (using exported function names like `GET_pets`, `POST_auth_login`).
19 | - Global middleware (`MIDDLEWARE_`) for logging and error handling.
20 | - In-memory data storage (arrays of pet and review objects).
21 | - Authentication and Authorization checks (using a mock plugin).
22 | - Logging (using a mock plugin).
23 | - Input validation using `use().body()` (including objects, arrays, files).
24 | - Handling various HTTP methods (GET, POST, PUT, DELETE).
25 | - Dynamic routing with path parameters (e.g., `/petBy/:id`).
26 | - Query parameter parsing for filtering, sorting, and pagination.
27 | - **File uploads** (handling multipart/form-data).
28 | - **WebSocket communication** for real-time updates.
29 | - Automatic API Documentation UI (Swagger UI).
30 | - API Documentation Export (JSON, YAML, Markdown).
31 | - Error Handling and Testing routes (`/error`).
32 | - Health Check route (`/health`).
33 | - Serving static/uploaded files (`/serve/*`, `/static/*`).
34 |
35 | ## Code Structure
36 |
37 | The original `app.jet.ts` file has been split into the following directories and files within the `src` folder:
38 |
39 | ```
40 |
41 | petshop-api/
42 | ├── src/
43 | │ ├── data/
44 | │ │ └── models.ts \# Defines data types and in-memory data arrays (pets, reviews).
45 | │ ├── middleware/
46 | │ │ └── global.ts \# Contains the global middleware (MIDDLEWARE\_) for logging and error handling.
47 | │ ├── plugins/ \# Directory for external plugins (mock examples)
48 | │ │ ├── auth.ts \# Mock authentication plugin (authenticate, verify, isAdmin).
49 | │ │ └── logging.ts \# Mock logging plugin (info, warn, error).
50 | │ ├── routes/
51 | │ │ ├── auth.ts \# Authentication routes (e.g., POST /auth/login).
52 | │ │ ├── live.ts \# WebSocket route (GET /live) and broadcasting logic.
53 | │ │ ├── pets.ts \# Pet management routes (CRUD, search, image upload, gallery).
54 | │ │ ├── reviews.ts \# Review management routes (GET, POST, DELETE reviews for pets).
55 | │ │ └── utils.ts \# Utility and miscellaneous routes (/, /stats, /error, /health, /export/docs, /upload, /serve, /static).
56 | │ ├── types.ts \# Defines TypeScript types used across the application (PetType, ReviewType).
57 | │ └── index.ts \# Main application entry point: Jetpath app initialization, configuration, plugin registration, imports.
58 | ├── package.json \# Project dependencies and scripts.
59 | ├── README.md \# This file.
60 | └── pet-shop-api-log.log \# Log file generated by the logger plugin (created on first run).
61 | └── uploads/ \# Directory for uploaded files (create this manually)
62 | ├── pet-images/ \# Directory for uploaded pet images (create this manually)
63 | └── general-files/ \# Directory for general file uploads (create this manually)
64 | └── served-content/ \# Directory for files served via /serve/\* (create this manually)
65 | └── public/ \# Directory for static files served via /static/\* (create this manually)
66 | └── static/ \# Subdirectory for static files (create this manually)
67 |
68 | ````
69 |
70 | ## Explanation of the Structure
71 |
72 | - **`src/index.ts`**: This is the application's bootstrapper. It sets up the core Jetpath application instance with global configurations (`apiDoc`, `globalHeaders`, `port`, `upgrade`). It initializes the database (in this case, conceptually preparing the in-memory data). It registers external plugins using `app.addPlugin()`. Crucially, it **imports** the other route and middleware files. Jetpath then automatically discovers and registers the exported route handlers (like `GET_pets`, `POST_auth_login`) and global middleware (`MIDDLEWARE_`) based on their naming conventions in these imported files.
73 | - **`src/types.ts`**: Centralizes the TypeScript interface/type definitions (`PetType`, `ReviewType`), promoting code consistency and clarity.
74 | - **`src/data/models.ts`**: Holds the application's data structures (the `PetType` and `ReviewType` definitions again for clarity, although imported from `types.ts`) and the in-memory data arrays (`pets`, `reviews`). In a real-world application, this layer would contain database connection logic and functions to interact with the database, abstracting data access away from the route handlers.
75 | - **`src/middleware/global.ts`**: Contains the single exported `MIDDLEWARE_` function. This function defines logic that runs for **every** incoming request (the pre-handler) and after the request is processed (the post-handler), handling cross-cutting concerns like logging, authentication checks, and error handling as demonstrated in the original sample. Jetpath automatically applies this global middleware due to its name.
76 | - **`src/plugins/`**: This directory represents external plugins. The original sample referenced `auth.ts` and `logging.ts`. These are included here as mock examples showing the expected structure (exporting plugin instances with specific methods like `authenticateUser`, `info`, `error`) that Jetpath's `app.addPlugin()` expects. The actual implementation details of these plugins would be more complex.
77 | - **`src/routes/`**: This directory contains files that group API endpoint handlers by functionality (auth, pets, reviews, live, utils). Each file exports functions following Jetpath's `METHOD_path$param` naming convention (e.g., `GET_pets`, `POST_auth_login`, `PUT_petBy$id`, `GET_live`).
78 | - `use(functionName).body(...)` is chained directly after the function definition to specify input validation for the request body.
79 | - `use(functionName).info(...)` is chained (often after `use().body()`) to provide documentation details for that specific endpoint, which Jetpath uses to generate the API documentation UI and export.
80 | - Route handlers access the request context (`ctx`) to get parameters, body, plugins, state, and send responses. They interact with the data layer (`../../data/models`).
81 | - **File System Directories**: `uploads/pet-images`, `uploads/general-files`, `served-content`, and `public/static` are directories used by the file upload and serving routes. You need to create these manually for those features to work correctly.
82 |
83 | This structure is designed to be easier for a beginner to navigate, understand the separation of concerns, and see how different parts of a Jetpath application fit together while still preserving the framework's unique conventions.
84 |
85 | ## Prerequisites
86 |
87 | * **Node.js** (v18 or higher recommended) or **Bun** (v1.0 or higher recommended). Ensure your chosen runtime is installed and accessible from your terminal.
88 | * A basic understanding of JavaScript or TypeScript.
89 | * Familiarity with fundamental backend and RESTful API concepts.
90 | * The **Jetpath framework** source code or package installed/accessible. You **must** update the `jetpath` dependency path in `package.json` to point to the correct location or package name of the Jetpath framework.
91 |
92 | ## Setup
93 |
94 | 1. **Obtain the Code:** Create the directory structure (`src`, `src/data`, `src/middleware`, `src/plugins`, `src/routes`, `src/routes/data`, `src/routes/middleware`, `src/routes/plugins`, `src/routes/routes`, `src/routes/types`) and files listed above, or clone the repository if this code is hosted in a Git repository:
95 | ```bash
96 | # If cloning from a repo
97 | git clone
98 | cd petshop-api
99 | ```
100 | *(Replace `` with the actual URL if applicable)*
101 |
102 | 2. **Create Necessary Directories:** Manually create the file system directories used by the file handling routes:
103 | ```bash
104 | mkdir -p uploads/pet-images
105 | mkdir -p uploads/general-files
106 | mkdir -p served-content
107 | mkdir -p public/static
108 | ```
109 |
110 | 3. **Update the `jetpath` dependency:**
111 | Open the `package.json` file and change the line `"jetpath": "file:../path/to/your/jetpath/dist"` to the correct path relative to your project's root directory where the Jetpath framework's `dist` directory is located, or replace it with the package name if Jetpath is published to an npm registry.
112 |
113 | 4. **Install dependencies:**
114 | Open your terminal in the project's root directory and run the appropriate command for your chosen runtime:
115 |
116 | * **If you will primarily use Node.js:**
117 | ```bash
118 | npm install
119 | ```
120 | This will install `better-sqlite3` (if needed for SQLite, although this sample uses in-memory arrays), `ts-node` (which allows Node.js to run TypeScript files directly), and `typescript`, plus any other dependencies defined in `package.json` (like placeholders for plugins).
121 |
122 | * **If you will primarily use Bun:**
123 | ```bash
124 | bun install
125 | ```
126 | Bun will handle the dependencies listed in `package.json`. Bun runs TypeScript files directly, so `ts-node` is not needed.
127 |
128 | ## Running the API
129 |
130 | You can run the API using either Node.js or Bun. The in-memory data will reset each time the server restarts.
131 |
132 | * **Using Node.js:**
133 | ```bash
134 | npm run start:node
135 | ```
136 | This script uses `ts-node` to execute the `src/index.ts` file with Node.js.
137 |
138 | * **Using Bun:**
139 | ```bash
140 | bun run src/index.ts
141 | # Alternatively, use the npm script alias:
142 | bun run start:bun
143 | ```
144 | Bun runs the `src/index.ts` file directly, using its native TypeScript capabilities.
145 |
146 | Once running, the server will print messages to the console indicating which port it's listening on (defaulting to 9000, as in the original sample) and the URL where you can access the API documentation.
147 |
148 | ## API Documentation (Swagger UI)
149 |
150 | An interactive API documentation interface (Swagger UI) is automatically generated and available while the server is running. Open your web browser and go to:
151 |
152 | `http://localhost:9000/api-doc`
153 |
154 | *(Note the port 9000 as configured in `src/index.ts`)*. This documentation is created by Jetpath based on the `apiDoc` configuration in `src/index.ts` and the `.info` properties you've added to the route handlers. It provides a convenient way to explore the API's endpoints and their expected parameters and responses. The documentation itself is secured with basic auth (admin/1234) as in the original sample.
155 |
156 | ## Example API Calls and Features
157 |
158 | You can interact with the API using command-line tools like `curl` or graphical clients like Postman or Insomnia. Since the original sample used in-memory data and mock plugins, you'll need to authenticate first to access protected routes (admin/1234).
159 |
160 | **1. Get API Status (GET /):**
161 |
162 | ```bash
163 | curl http://localhost:9000/
164 | ````
165 |
166 | *Expect basic API information.*
167 |
168 | **2. Authenticate (POST /auth/login):**
169 |
170 | ```bash
171 | curl -X POST http://localhost:9000/auth/login \
172 | -H "Content-Type: application/json" \
173 | -d '{"username": "admin", "password": "1234"}'
174 | ```
175 |
176 | *Expect a token in the response. You will need this token in the `Authorization: Bearer ` header for protected routes.*
177 |
178 | **3. Get all pets (GET /pets):**
179 |
180 | ```bash
181 | curl http://localhost:9000/pets
182 | # With pagination/filtering example:
183 | # curl "http://localhost:9000/pets?limit=5&species=dog&search=friendly"
184 | ```
185 |
186 | *Expect a list of pets.*
187 |
188 | **4. Add a new pet (POST /pets - requires Authentication and Admin role):**
189 |
190 | ```bash
191 | curl -X POST http://localhost:9000/pets \
192 | -H "Content-Type: application/json" \
193 | -H "Authorization: Bearer " \
194 | -d '{
195 | "name": "Buddy",
196 | "species": "Dog",
197 | "breed": "Beagle",
198 | "age": 2,
199 | "gender": "Male",
200 | "color": "Brown and White",
201 | "description": "Energetic and playful Beagle",
202 | "price": 300,
203 | "available": true,
204 | "tags": ["playful", "loyal"]
205 | }'
206 | ```
207 |
208 | *Replace `` with the token from the login response.*
209 |
210 | **5. Upload a pet image (POST /petImage/:id - requires Authentication and Admin role):**
211 |
212 | ```bash
213 | curl -X POST http://localhost:9000/petImage/pet-1 \
214 | -H "Authorization: Bearer " \
215 | -F "image=@/path/to/your/image.jpg" \
216 | -H "Content-Type: multipart/form-data"
217 | ```
218 |
219 | *Replace `pet-1` with a pet ID and `/path/to/your/image.jpg` with an image file path.*
220 |
221 | **6. Connect to WebSocket for live updates (GET /live):**
222 |
223 | Use a WebSocket client to connect to `ws://localhost:9000/live`. You should receive messages for certain events (like pet additions, though this might require adding broadcast calls in the route handlers).
224 |
225 | **7. Export API Documentation (GET /export/docs/:format):**
226 |
227 | ```bash
228 | curl http://localhost:9000/export/docs/json
229 | # or yaml, or markdown
230 | ```
231 |
232 | By exploring these modular files, you should gain a clearer understanding of how the different features of Jetpath demonstrated in the original sample can be organized into a more maintainable structure.
233 |
234 | ## Mock Plugins
235 |
236 | The sample relies on `authPlugin` and `jetLogger`. Simple mock versions are provided in `src/plugins/` to allow the code to run. In a real application, you would use actual plugin implementations.
237 |
--------------------------------------------------------------------------------
/example/chat.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Modern WebSocket Chat
7 |
8 |
9 |
10 |
248 |
249 |
250 |