UNPKG

@sm.ahmadi77/type-safe-url-s

Version:

A lightweight TypeScript library for writing URLs in a type-safe manner 👍.

85 lines (83 loc) 2.81 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { createRootPathObject: () => createRootPathObject, urlOf: () => urlOf }); module.exports = __toCommonJS(index_exports); var PATH_SEGMENTS_KEY = Symbol("PATH_SEGMENTS_KEY"); var OPTIONS_KEY = Symbol("OPTIONS_KEY"); var QUERY_PARAMS_KEY = Symbol("QUERY_PARAMS_KEY"); function createRootPathObject(options = {}) { return createPathObject([], options); } function createPathObject(pathSegments, options) { return new Proxy( (...pathParams) => { return createPathObject( [...pathSegments, ...pathParams.map(String)], options ); }, { get(_target, key) { if (key === PATH_SEGMENTS_KEY) return pathSegments; if (key === OPTIONS_KEY) return options; return createPathObject( [...pathSegments, String(key).replace("_", "-")], options ); } } ); } function urlOf(pathObject, queryParams) { const { baseUrl = "", autoAddLeadingSlash = true, autoAddTrailingSlash = false } = pathObject[OPTIONS_KEY]; const path = (() => { const result = `${autoAddLeadingSlash ? "/" : ""}${pathObject[PATH_SEGMENTS_KEY].map(encodeURIComponent).join("/")}${autoAddTrailingSlash ? "/" : ""}`; if (result === "//") return "/"; return result; })(); const searchParams = new URLSearchParams(); for (const [key, value] of Object.entries(queryParams ?? {})) { if (value === void 0 || value === null) continue; if (Array.isArray(value)) { for (const item of value) { if (item === void 0 || item === null) continue; searchParams.append(key, String(item)); } } else { searchParams.append(key, String(value)); } } const queryString = searchParams.toString(); if (queryString === "") return `${baseUrl}${path}`; return `${baseUrl}${path}?${queryString}`; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createRootPathObject, urlOf });