Compare commits

...

11 Commits

8 changed files with 284 additions and 68 deletions

52
changelog.md Normal file
View File

@ -0,0 +1,52 @@
# Changelog
## 2024-10-03 - 3.1.0 - feat(Smarturl)
Enhanced documentation and added method for property setting and chaining in Smarturl
- Added detailed comments to methods and interfaces for better code understanding.
- Introduced a method to set properties in a chainable manner.
## 2024-10-03 - 3.0.8 - fix(core)
Fix code formatting and indentation issues in smarturl.classes.smarturl.ts
- Improved code readability by fixing indentation and ensuring consistent formatting.
## 2022-07-27 - 3.0.0 to 3.0.7 - Core Updates
Maintenance and enhancement updates across multiple minor versions.
- **3.0.0**: Core updated with foundational changes.
- **3.0.1**: Further core updates with minor fixes.
- **3.0.2**: Continued enhancements and core updates.
- **3.0.3**: Additional core updates.
- **3.0.4**: Continued improvements in core functions.
- **3.0.5**: Ongoing core enhancements and updates.
- **3.0.6**: Maintenance improvements and stable updates.
## 2022-07-27 - 2.0.2 to 3.0.0 - Major Transition
Introduction of significant changes to the core.
- **2.0.2**: Introduced breaking changes with a switch to ESM (ECMAScript Modules).
## 2021-05-02 - 1.0.8 to 2.0.2 - Stability Updates
Updates focused on core stability and functionality.
- **1.0.8**: Breaking core updates were introduced to stabilize the platform.
- **2.0.0**: Core was updated for greater efficiency.
- **2.0.1**: Minor core improvements and updates.
## 2021-04-12 - 1.0.3 to 1.0.8 - Core Maintenance
Multiple updates for improving the core functionality.
- Incremental updates from 1.0.3 through 1.0.7 enhancing core stability.
## 2020-03-27 - 1.0.1 to 1.0.2 - Initial Core Enhancements
Early updates focusing on core aspects.
- Introduction of minor core improvements and fixes.
## 2015-10-21 - 0.0.1 to 0.0.4 - Project Initialization
Initial setup and foundational updates for the project.
- **0.0.1**: Project initiation and Travis integration.
- **0.0.3**: Creation of initial test infrastructure.
- **0.0.4**: Basic project setup completed.

View File

@ -2,17 +2,30 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smarturl",
"description": "a url parsing lib",
"npmPackagename": "@pushrocks/smarturl",
"description": "A library for parsing URLs in a detailed and flexible way.",
"npmPackagename": "@push.rocks/smarturl",
"license": "MIT",
"projectDomain": "push.rocks"
"projectDomain": "push.rocks",
"keywords": [
"URL parsing",
"TypeScript",
"node.js",
"web development",
"URL manipulation",
"search parameters",
"HTTP",
"HTTPS"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}

View File

@ -1,8 +1,8 @@
{
"name": "@pushrocks/smarturl",
"version": "3.0.6",
"name": "@push.rocks/smarturl",
"version": "3.1.0",
"private": false,
"description": "a url parsing lib",
"description": "A library for parsing URLs in a detailed and flexible way.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@ -34,5 +34,20 @@
],
"browserslist": [
"last 1 chrome versions"
]
],
"keywords": [
"URL parsing",
"TypeScript",
"node.js",
"web development",
"URL manipulation",
"search parameters",
"HTTP",
"HTTPS"
],
"homepage": "https://code.foss.global/push.rocks/smarturl",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smarturl.git"
}
}

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

146
readme.md
View File

@ -1,39 +1,131 @@
# @pushrocks/smarturl
# @push.rocks/smarturl
a url parsing lib
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smarturl)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smarturl)
* [github.com (source mirror)](https://github.com/pushrocks/smarturl)
* [docs (typedoc)](https://pushrocks.gitlab.io/smarturl/)
## Install
## Status for master
To install `@push.rocks/smarturl`, you'll need Node.js and npm on your system. Once you have those set up, run the following command in your terminal:
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smarturl/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smarturl/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smarturl)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smarturl)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smarturl)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smarturl)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smarturl)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
```bash
npm install @push.rocks/smarturl --save
```
This will add `@push.rocks/smarturl` to your project's dependencies.
## Usage
Use TypeScript for best in class intellisense
`@push.rocks/smarturl` is a library designed to simplify the parsing and manipulation of URLs within your TypeScript projects. Below is an overview of how you can leverage this library effectively in various scenarios.
## Contribution
### Basic URL Parsing
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
To start parsing URLs, you first need to import `@push.rocks/smarturl` into your TypeScript file:
For further information read the linked docs at the top of this readme.
```typescript
import { Smarturl } from '@push.rocks/smarturl';
```
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
Now, you can parse a URL string and access its components:
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
```typescript
const myUrl = Smarturl.createFromUrl('https://www.example.com:8080/path?query=string#hash');
console.log(myUrl.href); // https://www.example.com:8080/path?query=string#hash
console.log(myUrl.protocol); // https:
console.log(myUrl.host); // www.example.com:8080
console.log(myUrl.pathname); // /path
console.log(myUrl.search); // ?query=string
console.log(myUrl.hash); // #hash
console.log(myUrl.searchParams); // { query: 'string' }
```
### Modifying Search Parameters
`@push.rocks/smarturl` makes it easy to modify search parameters of a URL:
```typescript
// Creating a URL with initial search parameters
const myUrl = Smarturl.createFromUrl('https://www.example.com', {
searchParams: {
page: '1',
filter: 'none',
},
});
// Adding or updating search parameters
myUrl.searchParams['filter'] = 'newVal';
myUrl.searchParams['newParam'] = 'value';
console.log(myUrl.toString()); // https://www.example.com:443/?page=1&filter=newVal&newParam=value
```
### Complex URL Creation
Sometimes you may need to create a URL from parts:
```typescript
let myUrl = new Smarturl();
myUrl.protocol = 'https';
myUrl.hostname = 'www.example.com';
myUrl.port = '3000';
myUrl.pathname = '/path/to/resource';
myUrl.searchParams = {
key: 'value',
another: 'parameter'
};
console.log(myUrl.toString()); // Prints the full URL
```
### Handling Username and Password in URL
You can also include authentication details within the URL:
```typescript
const myUrl = Smarturl.createFromUrl('https://user:password@www.example.com');
console.log(myUrl.username); // user
console.log(myUrl.password); // password
```
### Working with URL Paths and Hashes
Manipulating paths and hashes is straightforward:
```typescript
const myUrl = Smarturl.createFromUrl('https://www.example.com/path/to/resource');
myUrl.hash = 'section1';
console.log(myUrl.toString()); // https://www.example.com:443/path/to/resource#section1
```
### URL Encoding and Decoding
When working with URLs, encoding and decoding of search parameters is handled automatically by the library. This ensures that the URL remains valid and interpretable by browsers and servers.
```typescript
const myUrl = Smarturl.createFromUrl('https://www.example.com');
myUrl.searchParams['redirect_uri'] = 'https://www.redirect.com/path';
console.log(myUrl.toString()); // Automatically encodes the URI
```
In addition to basic parsing and manipulation, `@push.rocks/smarturl` provides methods for deep manipulation of URLs, aiding in scenarios where complex URL operations are needed.
By understanding and utilizing these features, you can handle most URL-related tasks within your TypeScript applications with ease, ensuring that URLs are constructed, interpreted, and modified in a consistent and error-free manner.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@ -1,8 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@pushrocks/smarturl',
version: '3.0.6',
description: 'a url parsing lib'
name: '@push.rocks/smarturl',
version: '3.1.0',
description: 'A library for parsing URLs in a detailed and flexible way.'
}

View File

@ -1,5 +1,7 @@
// Import necessary plugins (if any are used in the module)
import * as plugins from './smarturl.plugins.js';
// Interface representing the structure of a URL object
export interface IUrlObject {
href: string;
origin: string;
@ -16,31 +18,37 @@ export interface IUrlObject {
hash: string;
}
// Interface representing the search parameters as a key-value pair object
export interface ISearchParams {
[key: string]: string;
}
// Main Smarturl class implementing the IUrlObject interface
export class Smarturl implements IUrlObject {
// Static method to create a Smarturl instance from a URL string
public static createFromUrl(
urlArg: string,
optionsArg?: {
searchParams?: ISearchParams;
}
): Smarturl {
// Parse the URL string using the built-in URL class
const parsedUrlInstance = new URL(urlArg);
const searchParams: ISearchParams = {};
// enrichment
// Array to hold key-value pairs of search parameters
const searchParamPairs: {
key: string;
value: string;
}[] = []
}[] = [];
// If the URL has search parameters, parse them into key-value pairs
if (parsedUrlInstance.search) {
parsedUrlInstance.search
.replace('?', '')
.split('&')
.replace('?', '') // Remove the '?' at the beginning
.split('&') // Split the query string into individual parameters
.map((searchParamPair) => {
// Split each parameter into key and value and add to the array
searchParamPairs.push({
key: searchParamPair.split('=')[0],
value: searchParamPair.split('=')[1],
@ -48,15 +56,19 @@ export class Smarturl implements IUrlObject {
});
}
// Convert the array of key-value pairs into an object
for (const searchParamPair of searchParamPairs) {
searchParams[searchParamPair.key] = searchParamPair.value;
}
// Merge any additional search parameters provided in optionsArg
if (optionsArg?.searchParams) {
for (const key of Object.keys(optionsArg.searchParams)) {
searchParams[key] = optionsArg.searchParams[key];
}
}
// Reconstruct the path with updated search parameters
let path = parsedUrlInstance.pathname || '';
if (Object.keys(searchParams).length > 0) {
path += '?';
@ -71,8 +83,9 @@ export class Smarturl implements IUrlObject {
}
}
// Create an IUrlObject containing all parts of the URL
const parsedUrl: IUrlObject = {
...parsedUrlInstance,
...parsedUrlInstance, // Spread operator to include all properties from parsedUrlInstance
href: parsedUrlInstance.href,
origin: parsedUrlInstance.origin,
protocol: parsedUrlInstance.protocol,
@ -81,32 +94,35 @@ export class Smarturl implements IUrlObject {
host: parsedUrlInstance.host,
hostname: parsedUrlInstance.hostname,
port: parsedUrlInstance.port,
path,
path, // Updated path with new search parameters
pathname: parsedUrlInstance.pathname,
search: parsedUrlInstance.search,
searchParams,
searchParams, // The searchParams object we constructed
hash: parsedUrlInstance.hash,
};
// Infer default ports if none are specified based on the protocol
if (!parsedUrl.port && parsedUrl.protocol === 'https:') {
// console.log(`inferring port 443 for "https:"`);
parsedUrl.port = '443';
}
if (!parsedUrl.port && parsedUrl.protocol === 'http:') {
// console.log(`inferring port 80 for "http:"`);
parsedUrl.port = '80';
}
// Create a new Smarturl instance and assign the parsed URL properties
const returnSmarturl = new Smarturl();
Object.assign(returnSmarturl, parsedUrl);
return returnSmarturl;
}
public static createFromParsedUrl(parsedUrlArg: IUrlObject) {
const returnSmarturl = new Smarturl();
Object.assign(returnSmarturl, parsedUrlArg);
Object.assign(returnSmarturl, parsedUrl); // Copy all properties from parsedUrl to returnSmarturl
return returnSmarturl;
}
// INSTANCE
// Static method to create a Smarturl instance from an existing IUrlObject
public static createFromParsedUrl(parsedUrlArg: IUrlObject): Smarturl {
const returnSmarturl = new Smarturl();
Object.assign(returnSmarturl, parsedUrlArg); // Copy all properties from parsedUrlArg to returnSmarturl
return returnSmarturl;
}
// INSTANCE PROPERTIES (matching IUrlObject interface)
href: string;
origin: string;
protocol: string;
@ -121,12 +137,35 @@ export class Smarturl implements IUrlObject {
searchParams: ISearchParams;
hash: string;
// Constructor initializes searchParams as an empty object
constructor() {
this.searchParams = {};
}
toString() {
let userpart = ``;
// Method to create an independent clone of the current Smarturl instance
clone(): Smarturl {
const clonedInstance = new Smarturl();
Object.assign(clonedInstance, this); // Copy all properties to the new instance
clonedInstance.searchParams = { ...this.searchParams }; // Shallow copy of searchParams to prevent shared references
return clonedInstance;
}
/**
* Typed method to set a property and return the instance for chaining.
* @param prop - The property name to set (must be a key of Smarturl)
* @param value - The value to assign to the property
* @returns The Smarturl instance for method chaining
*/
set<K extends keyof this>(prop: K, value: this[K]): this {
this[prop] = value; // Set the property to the new value
return this; // Return the instance for chaining
}
// Method to convert the Smarturl instance back into a URL string
toString(): string {
let userpart = ``; // Initialize the user part of the URL (username and password)
// Construct the user part based on the presence of username and password
if (this.username && !this.password) {
userpart = `${this.username}@`;
}
@ -134,7 +173,7 @@ export class Smarturl implements IUrlObject {
userpart = `${this.username}:${this.password}@`;
}
// Construct and return the full URL string
return `${this.protocol}//${userpart}${this.hostname}:${this.port}${this.path}`;
}
}

View File

@ -3,8 +3,12 @@
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
}
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}