Skip to content

Commit

Permalink
Fix export (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
teaddict authored Jan 25, 2025
1 parent f0c06fa commit 957a90b
Show file tree
Hide file tree
Showing 11 changed files with 210 additions and 77 deletions.
14 changes: 11 additions & 3 deletions .babelrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,17 @@
"presets": [
["@babel/preset-env", {
"targets": {
"node": "current"
}
"node": "current",
"browsers": "> 0.25%, not dead"
},
"modules": "umd"
}]
],
"plugins": ["add-module-exports"]
"plugins": [
["@babel/plugin-transform-modules-umd", {
"globals": {
"swiss-ssn": "SwissSSN"
}
}]
]
}
46 changes: 46 additions & 0 deletions .github/PR_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
You are a GitHub Pull Request analyst. Your task is to create a concise, well-structured Markdown summary of a PR to help reviewers quickly understand the changes and their implications.

You will be given JSON data about the PR, including commits, descriptions, and file changes.

Analyze this data to extract key information for your summary, focusing on commit messages and significant code changes.

Your output should be a Markdown document with the following structure:

### Why:
### What:
### How can it be used:
### How did you test it:
### Notes for the reviewer:

Guidelines for each section:

1. **Why:**
- Summarize the motivation for the change in 1-2 sentences.
- Start with an action verb (e.g., Fixes, Enhances, Refactors).
- Do not mention the project name or that this is a pull request.

2. **What:**
- List the main changes made, focusing on the most impactful ones.
- Limit to 2-3 concise bullet points.

3. **How can it be used:**
- Briefly describe the effect of the changes.
- Include short code snippets if relevant, enclosed in triple backticks ```.

4. **How did you test it:**
- Mention the testing methods used in 1-2 sentences.
- Explain how these tests validate the changes.

5. **Notes for the reviewer:**
- Provide any additional important information in 1-2 sentences.
- Highlight any areas needing special attention.

Writing instructions:

- Be direct and succinct.
- Use an assertive tone without hedging language.
- Maintain the specified section names and order.
- Keep each section brief, with a maximum of 2-3 items or sentences.
- Use code blocks only in "How can it be used" if necessary.

Begin your response with "### Why:" and proceed through all sections in order. Your goal is to offer a clear, concise summary to assist the PR reviewer.
25 changes: 25 additions & 0 deletions .github/workflows/pr-describe-ai.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# name: OpenAI PR Description Generator

# on:
# pull_request:
# types:
# - opened
# - synchronize

# permissions:
# pull-requests: write
# contents: read

# jobs:
# pull-request:
# runs-on: ubuntu-latest
# steps:
# - uses: actions/checkout@v3
# - name: Generate PR Description
# uses: Ant0wan/openai-pr@v1
# with:
# api-key: ${{ secrets.OPENAI_API_KEY }}
# model: "gpt-4o-mini"
# template-filepath: ".github/PR_TEMPLATE.md"
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,5 @@ build/Release
# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules/

.DS_Store
26 changes: 23 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ A lightweight JavaScript library for validating and generating Swiss National Id
- Modern ES Module support
- Full test coverage
- TypeScript-friendly JSDoc annotations
- Browser-ready UMD bundle

## Installation

Expand All @@ -25,7 +26,7 @@ pnpm add swiss-ssn

## Usage

### ES Modules (Recommended)
### ES Modules (Node.js)
```js
import SwissSSN from 'swiss-ssn';

Expand All @@ -38,11 +39,12 @@ const newSSN = SwissSSN.generateSSN();
console.log(newSSN); // e.g., '756.1234.5678.90'
```

### Browser (UMD)
### Browser
```html
<!-- Use the minified UMD bundle -->
<script src="https://unpkg.com/swiss-ssn/dist/swiss-ssn.min.js"></script>
<script>
// Validate a SSN
// The SwissSSN class is available globally
const isValid = SwissSSN.validateSSN('756.9217.0769.85');
console.log(isValid); // true
Expand All @@ -52,6 +54,17 @@ console.log(newSSN); // e.g., '756.1234.5678.90'
</script>
```

### Browser (ES Modules)
```html
<!-- Use as ES Module in modern browsers -->
<script type="module">
import SwissSSN from 'https://unpkg.com/swiss-ssn/dist/swiss-ssn.js';
const isValid = SwissSSN.validateSSN('756.9217.0769.85');
console.log(isValid);
</script>
```

## API Reference

### `validateSSN(ssn: string): boolean`
Expand Down Expand Up @@ -101,6 +114,13 @@ Test Online

## Changelog

### 1.0.3
- Fixed browser compatibility issues with UMD bundle
- Added proper global exports for browser environments
- Improved documentation for browser usage
- Added ES Module example for modern browsers
- Updated build configuration for better browser support

### 1.0.2
- Modernized codebase with ES Modules
- Added Jest for testing
Expand Down
154 changes: 86 additions & 68 deletions dist/swiss-ssn.js
Original file line number Diff line number Diff line change
@@ -1,79 +1,97 @@
"use strict";

/**
* Project: swiss-ssn
* Purpose: Validate and generate Swiss SSN's according to http://www.sozialversicherungsnummer.ch/aufbau-neu.htm
* Author: teaddict
* @version 1.0.2
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class SwissSSN {
static #COUNTRY_CODE = [7, 5, 6];
static #MAX_VALUE = 10;
static #SSN_LENGTH = 13;
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.swissSsn = mod.exports;
}
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports) {
"use strict";

/**
* Validates parameter given SSN. Returns true if SSN is valid, otherwise false.
* @param {string} ssn - For example '756.9217.0769.85' or '7569217076985'
* @returns {boolean}
* Project: swiss-ssn
* Purpose: Validate and generate Swiss SSN's according to http://www.sozialversicherungsnummer.ch/aufbau-neu.htm
* Author: teaddict
* @version 1.0.2
*/
static validateSSN(ssn) {
if (!ssn) {
return false;
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
class SwissSSN {
static #COUNTRY_CODE = [7, 5, 6];
static #MAX_VALUE = 10;
static #SSN_LENGTH = 13;

/**
* Validates parameter given SSN. Returns true if SSN is valid, otherwise false.
* @param {string} ssn - For example '756.9217.0769.85' or '7569217076985'
* @returns {boolean}
*/
static validateSSN(ssn) {
if (!ssn) {
return false;
}
const parsedSSN = this.#parse(ssn);
if (parsedSSN.length !== this.#SSN_LENGTH) {
return false;
}
const checkDigit = this.#getCheckDigit(parsedSSN);
return parseInt(parsedSSN[12], 10) === checkDigit;
}
const parsedSSN = this.#parse(ssn);
if (parsedSSN.length !== this.#SSN_LENGTH) {
return false;

/**
* Creates a valid SSN using random numbers.
* @returns {string} - valid ssn.
*/
static generateSSN() {
const randomNumbers = Array.from({
length: 9
}, () => Math.floor(Math.random() * this.#MAX_VALUE));
const ssnWithoutCheckDigit = [...this.#COUNTRY_CODE, ...randomNumbers];
const checkDigit = this.#getCheckDigit(ssnWithoutCheckDigit);
const unformattedSSN = [...ssnWithoutCheckDigit, checkDigit];
return this.#ssnFormatter(unformattedSSN);
}
const checkDigit = this.#getCheckDigit(parsedSSN);
return parseInt(parsedSSN[12], 10) === checkDigit;
}

/**
* Creates a valid SSN using random numbers.
* @returns {string} - valid ssn.
*/
static generateSSN() {
const randomNumbers = Array.from({
length: 9
}, () => Math.floor(Math.random() * this.#MAX_VALUE));
const ssnWithoutCheckDigit = [...this.#COUNTRY_CODE, ...randomNumbers];
const checkDigit = this.#getCheckDigit(ssnWithoutCheckDigit);
const unformattedSSN = [...ssnWithoutCheckDigit, checkDigit];
return this.#ssnFormatter(unformattedSSN);
}
/**
* Calculate check digit for SSN
* @private
*/
static #getCheckDigit(ssn) {
const total = [...ssn].slice(0, 12).reduce((sum, digit, index) => {
const multiplier = index % 2 === 0 ? 1 : 3;
return sum + parseInt(digit, 10) * multiplier;
}, 0);
return total % 10 === 0 ? 0 : Math.ceil(total / 10) * 10 - total;
}

/**
* Calculate check digit for SSN
* @private
*/
static #getCheckDigit(ssn) {
const total = [...ssn].slice(0, 12).reduce((sum, digit, index) => {
const multiplier = index % 2 === 0 ? 1 : 3;
return sum + parseInt(digit, 10) * multiplier;
}, 0);
return total % 10 === 0 ? 0 : Math.ceil(total / 10) * 10 - total;
}
/**
* Format SSN with dots
* @private
*/
static #ssnFormatter(ssn) {
const ssnString = ssn.map(String);
return `756.${ssnString.slice(3, 7).join("")}.${ssnString.slice(7, 11).join("")}.${ssnString.slice(11, 13).join("")}`;
}

/**
* Format SSN with dots
* @private
*/
static #ssnFormatter(ssn) {
const ssnString = ssn.map(String);
return `756.${ssnString.slice(3, 7).join('')}.${ssnString.slice(7, 11).join('')}.${ssnString.slice(11, 13).join('')}`;
/**
* Parse SSN string by removing all non-digit characters
* @private
*/
static #parse(ssn) {
return ssn.replace(/\D/g, "");
}
}

/**
* Parse SSN string by removing all non-digit characters
* @private
*/
static #parse(ssn) {
return ssn.replace(/\D/g, '');
// Export for different environments
if (typeof window !== 'undefined') {
window.SwissSSN = SwissSSN; // Browser global
}
}
exports.default = SwissSSN;
module.exports = exports.default;
var _default = _exports.default = SwissSSN;
});
2 changes: 1 addition & 1 deletion dist/swiss-ssn.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ export const build = () => {
.pipe(uglify({
output: {
comments: 'some'
},
compress: {
pure_getters: true
},
mangle: {
reserved: ['SwissSSN']
}
}))
.pipe(rename({ suffix: '.min' }))
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"description": "Small utility for validating and generating Swiss national identification number.",
"author": "teaddict",
"main": "dist/swiss-ssn.js",
"type": "module",
"keywords": [
"Swiss",
"SSN",
Expand All @@ -29,6 +28,7 @@
"@babel/cli": "^7.23.9",
"@babel/core": "^7.23.9",
"@babel/eslint-parser": "^7.23.10",
"@babel/plugin-transform-modules-umd": "^7.23.3",
"@babel/preset-env": "^7.23.9",
"@babel/register": "^7.23.7",
"babel-jest": "^29.7.0",
Expand Down
9 changes: 8 additions & 1 deletion src/swiss-ssn.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* @version 1.0.2
*/

export default class SwissSSN {
class SwissSSN {
static #COUNTRY_CODE = [7, 5, 6]
static #MAX_VALUE = 10
static #SSN_LENGTH = 13
Expand Down Expand Up @@ -79,3 +79,10 @@ export default class SwissSSN {
return ssn.replace(/\D/g, "")
}
}

// Export for different environments
if (typeof window !== "undefined") {
window.SwissSSN = SwissSSN // Browser global
}

export default SwissSSN

0 comments on commit 957a90b

Please sign in to comment.