### Install npm package Source: https://github.com/inventaire/isbn3/blob/main/README.md Install the isbn3 library using npm. This is the primary method for Node.js environments. ```sh npm install isbn3 ``` -------------------------------- ### Example GroupInfo Object Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/types.md Illustrates a concrete example of the GroupInfo structure for the English language group. ```typescript { name: 'English language', ranges: [ ['00', '19'], ['200', '227'], ['229', '368'], // ... more ranges ] } ``` -------------------------------- ### Run Test Suite Source: https://github.com/inventaire/isbn3/blob/main/README.md Execute the lint and test suite for the project. Ensure you have npm installed. ```sh npm test ``` -------------------------------- ### Browser Usage Example Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md Demonstrates how to use the ISBN3 library in a browser by including the script and calling the parse function. ```html ``` -------------------------------- ### ISBN CLI Success Example Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Demonstrates a successful ISBN parsing operation with the `isbn` command. The exit code 0 indicates success. ```bash # Success $ isbn 978-4-87311-336-4 13h 978-4-87311-336-4 echo $? # 0 ``` -------------------------------- ### ISBN Checksum Success Example Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Shows a successful ISBN checksum calculation using the `isbn-checksum` command. The exit code 0 indicates success. ```bash # Success $ isbn-checksum 978-4-87311-336-1 {"input":"978-4-87311-336-1",...} echo $? # 0 ``` -------------------------------- ### Audit ISBN with Issue Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md This example demonstrates auditing an ISBN that has a detected issue. The output JSON will include a 'clues' array detailing the problem. ```bash # Audit ISBN with issue isbn-audit 9781090648525 # Output: { # "source": "9781090648525", # "validIsbn": true, # "groupname": "English language", # "clues": [ # { # "message": "Possible prefix error", # "candidate": {...} # } # ] # } ``` -------------------------------- ### Batch Process ISBNs Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md An example demonstrating how to process a list of ISBNs, filtering out invalid ones and extracting the ISBN-13 in hyphenated format. ```javascript const isbns = ['978-...', '979-...', 'invalid'] const valid = isbns .map(ISBN.parse) .filter(Boolean) .map(isbn => isbn.isbn13h) ``` -------------------------------- ### ISBN CLI Invalid ISBN Example Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Shows an example of an invalid ISBN input to the `isbn` command. The exit code 1 signifies an invalid ISBN or unknown format. ```bash # Invalid ISBN $ isbn not-an-isbn 13h invalid ISBN echo $? # 1 ``` -------------------------------- ### ISBN CLI Unknown Format Example Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Illustrates an unknown format error with the `isbn` command. The exit code 1 indicates an invalid ISBN or unknown format. ```bash # Unknown format $ isbn 978-4-87311-336-4 invalid-format unknown format echo $? # 1 ``` -------------------------------- ### Update isbn3 to Latest Version Source: https://github.com/inventaire/isbn3/blob/main/README.md Install the latest version of the isbn3 package to get the most up-to-date group data. Be aware of potential breaking changes when updating major versions. ```sh npm install isbn3@latest ``` -------------------------------- ### Convert 979-prefix ISBN to ISBN-13 (Compact) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn13.md Converts a 979-prefixed ISBN to its ISBN-13 compact representation. This example highlights support for the less common 979 prefix. ```javascript const ISBN = require('isbn3') // 979-prefix ISBN (no ISBN-10 equivalent) const result5 = ISBN.asIsbn13('979-10-96908-02-8') // '9791096908028' ``` -------------------------------- ### Format 979-prefix ISBN Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/hyphenate.md Formats an ISBN-13 that starts with the 979 prefix. ```javascript // 979-prefix ISBN const result5 = ISBN.hyphenate('9791096908028') // '979-10-96908-02-8' ``` -------------------------------- ### Filtering Groups by Prefix Family and Name Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/groups.md Illustrates how to filter the `groups` object to find all entries that start with a specific ISBN-13 prefix family (e.g., '978-') and match a given group name. This is useful for finding all groups related to a particular language or region. ```javascript // Find groups for a specific prefix family const allEnglishGroups = Object.entries(ISBN.groups) .filter(([key]) => key.startsWith('978-')) .filter(([_, info]) => info.name === 'English language') // Returns multiple entries for different English-speaking regions ``` -------------------------------- ### Migrating from isbn2 to isbn3 Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Demonstrates the compatible import and usage of the isbn3 library, showing how to replace the older isbn2 import. It highlights that function signatures and return types remain compatible. ```javascript // isbn2 const isbn = require('isbn2') // isbn3 (compatible, but recommended to import at top) const ISBN = require('isbn3') // All function signatures and return types are compatible // Some improvements in error recovery and performance ``` -------------------------------- ### Project File Structure Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/MANIFEST.md Overview of the directory and file layout for the project's documentation. ```text output/ ├── INDEX.md (Navigation) ├── README.md (Overview) ├── DOCUMENTATION_SUMMARY.md (Summary) ├── MANIFEST.md (This file) ├── quick-start.md (Getting started) ├── MODULE_INDEX.md (Architecture) ├── types.md (Type definitions) ├── endpoints.md (CLI reference) ├── errors.md (Error handling) ├── configuration.md (Setup) └── api-reference/ ├── parse.md (Parse function) ├── asIsbn13.md (ISBN-13 conversion) ├── asIsbn10.md (ISBN-10 conversion) ├── hyphenate.md (Formatting) ├── audit.md (Error detection) ├── groups.md (Group data) └── internal-modules.md (Internal utilities) ``` -------------------------------- ### Basic TypeScript Usage Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Demonstrates how to import and use the 'parse' function from the 'isbn3' library in a TypeScript project. ```typescript import { parse, ISBN } from 'isbn3' const result: ISBN | null = parse(input) ``` -------------------------------- ### Build Browserified Distribution Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Command to build the browser-compatible JavaScript distribution file for the ISBN3 library. ```bash npm run update-dist ``` -------------------------------- ### Retrieve ISBN Group Information Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md Get details about an ISBN's group identifier. Returns null if the input is not a valid ISBN. ```javascript function getGroupInfo(isbn) { const parsed = ISBN.parse(isbn) if (!parsed) return null const key = `${parsed.prefix}-${parsed.group}` return { key, ...ISBN.groups[key] } } ``` -------------------------------- ### Main Entry Point Exports Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/MODULE_INDEX.md All public functionality is exported from this single entry point. ```javascript module.exports = { parse, audit, hyphenate, asIsbn13, asIsbn10, groups } ``` -------------------------------- ### Get checksum value only Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md Use the 'c' option to retrieve only the calculated checksum digit for an ISBN-13. This is useful for scripting or when only the checksum value is needed. ```bash isbn-checksum 978-4-87311-336 c # Output: 4 ``` -------------------------------- ### Run Linting with StandardJS Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Executes the StandardJS linter to check code style and identify potential issues. ```bash npm run lint ``` -------------------------------- ### Handle 979-prefix ISBN (Cannot Convert to ISBN-10) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn10.md Demonstrates that 979-prefixed ISBNs cannot be converted to ISBN-10 and will result in null. Requires the 'isbn3' module. ```javascript const ISBN = require('isbn3') // 979-prefix ISBN (cannot convert to ISBN-10) const result5 = ISBN.asIsbn10('979-10-96908-02-8') // null ``` ```javascript const ISBN = require('isbn3') // 979-prefix with hyphen param const result6 = ISBN.asIsbn10('979-10-96908-02-8', true) // null ``` -------------------------------- ### Accessing Group Information by Prefix Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/groups.md Demonstrates how to access specific group information using the full ISBN group prefix as a key. This is useful for retrieving details about a known group. ```javascript const ISBN = require('isbn3') // Access English language group (978 prefix, group 0) const englishGroup = ISBN.groups['978-0'] // { // name: 'English language', // ranges: [ // ['00', '19'], // ['200', '227'], // ['2280', '2289'], // ['229', '368'], // ... // ] // } // Access Japanese group (978 prefix, group 4) const japaneseGroup = ISBN.groups['978-4'] // { // name: 'Japan', // ranges: [ // ['00', '19'], // ['200', '299'], // ... // ] // } // Access French group (979 prefix, group 10) const frenchGroup = ISBN.groups['979-10'] // { // name: 'France', // ranges: [ // ['00', '29'], // ['300', '399'], // ... // ] // } ``` -------------------------------- ### ISBN Checksum Invalid ISBN Example Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Illustrates an invalid ISBN input for the `isbn-checksum` command. The exit code 1 signifies an invalid ISBN or calculation failure. ```bash # Invalid ISBN $ isbn-checksum not-valid invalid ISBN despite recalculated checksum echo $? # 1 ``` -------------------------------- ### Audit Malformed ISBN Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md When ISBN.parse returns null for a seemingly valid ISBN, use ISBN.audit() to get clues about the parsing issue. This snippet demonstrates how to log these clues. ```javascript const malformedIsbn = 'some-isbn-string' const parsed = ISBN.parse(malformedIsbn) if (!parsed) { const audit = ISBN.audit(malformedIsbn) console.log('Clues:', audit.clues) } ``` -------------------------------- ### Iterating Over All Groups Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/groups.md Shows how to iterate through all available ISBN groups using `Object.keys()` and log their prefixes and names. This is useful for exploring the entire dataset. ```javascript // Iterate over all groups Object.keys(ISBN.groups).forEach(prefix => { const group = ISBN.groups[prefix] console.log(`${prefix}: ${group.name}`) }) ``` -------------------------------- ### Process ISBN with Non-Standard Separators Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md The 'isbn' command can handle ISBNs with non-standard separators by ignoring them and applying the specified format. This example formats an ISBN-13 with embedded non-digit characters. ```bash isbn 978-hello-1491-world-7431-7 13h # Output: 978-1-4915-7431-7 ``` -------------------------------- ### Get ISBN Group Information Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/internal-modules.md Locates the ISBN group for a given ISBN-13 string and identifies the publisher/article split point. It can also process 10-digit ISBNs by prepending '978'. ```javascript const getGroup = require('./lib/get_group') const result = getGroup('9784873113364') // { // group: '4', // groupPrefix: '978-4', // ranges: [['00', '19'], ['200', '299'], ...], // restAfterGroup: '873113364' // } ``` -------------------------------- ### Import with TypeScript Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/MODULE_INDEX.md Import various components including parse, audit, ISBN, and ISBNAudit using TypeScript syntax. ```typescript import { parse, audit, ISBN, ISBNAudit } from 'isbn3' ``` -------------------------------- ### Node.js ES6 Module Import Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Illustrates importing the ISBN3 library using ES6 import syntax, which may require a bundler or specific Node.js flags. ```javascript import * as ISBN from 'isbn3' ``` -------------------------------- ### Parse ISBN with Fallback Validation Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md Use this function to get the canonical ISBN-13, falling back to auditing for suggestions if direct parsing fails. It returns null if no valid ISBN-13 can be determined. ```javascript function getCanonicalIsbn(input) { const parsed = ISBN.parse(input) if (parsed) { return parsed.isbn13 } // Fallback: try to audit for suggestions const audit = ISBN.audit(input) if (audit.clues.length > 0) { return audit.clues[0].candidate?.isbn13 } return null } ``` -------------------------------- ### Audit an ISBN String Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/audit.md Call the audit function with an ISBN string to get diagnostic clues about its validity and potential corrections. This function handles both ISBN-10 and ISBN-13 formats, with or without hyphens. ```javascript audit("978-0-306-40615-7") ``` -------------------------------- ### ISBN Audit EPIPE Handling Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Demonstrates how the `isbn-audit` command handles broken pipes gracefully. The exit code remains 0 even when output is redirected and the pipe is broken. ```bash # EPIPE error is caught and handled, exit code is 0 isbn-audit < large_file.txt | head -1 ``` -------------------------------- ### Handle Invalid ISBN Formats Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md When an ISBN is invalid due to incorrect characters, group/publisher ranges, or failed check digit validation, the parse function returns null. Use the audit function to get suggestions for correction. ```javascript const result = ISBN.parse(input) if (result === null) { // Try to audit for suggestions const audit = ISBN.audit(input) if (audit.clues.length > 0) { console.log('Suggestions:', audit.clues[0].candidate) } } ``` -------------------------------- ### Initialize and Update ISBN Parsing Source: https://github.com/inventaire/isbn3/blob/main/index.html Sets up event listeners for ISBN input, debounces updates, and initializes the display on page load. Manages URL query parameters for the ISBN. ```javascript const queryIsbn = new URLSearchParams(window.location.search).get('isbn') const debouncedUpdate = debounce(update, 100) if (queryIsbn) isbnInput.value = queryIsbn window.addEventListener('load', function () { update() isbnInput.addEventListener('keyup', debouncedUpdate) }) ``` -------------------------------- ### TypeScript ISBN Parsing and Auditing Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md Demonstrates how to parse an ISBN string, log its details, and audit it using the isbn3 library in TypeScript. ```typescript import { parse, ISBN, audit, ISBNAudit } from 'isbn3' function processIsbn(input: string): void { const result: ISBN | null = parse(input) if (!result) { console.error('Invalid ISBN') return } console.log(`ISBN-13: ${result.isbn13h}`) console.log(`Country: ${result.groupname}`) if (result.isbn10) { console.log(`ISBN-10: ${result.isbn10h}`) } } function auditIsbn(input: string): ISBNAudit { return audit(input) } ``` -------------------------------- ### Import Individual Modules (CommonJS) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/MODULE_INDEX.md While possible, importing individual modules directly is not recommended. Use this for specific needs if necessary. ```javascript // Individual modules (not recommended) const parse = require('isbn3/lib/parse') const audit = require('isbn3/lib/audit') const groups = require('isbn3/lib/groups') ``` -------------------------------- ### CLI Command for ISBN Checksum Calculation Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md Use the 'isbn-checksum' command to calculate and verify ISBN checksums. ```bash isbn-checksum [option] ``` -------------------------------- ### CLI Command for ISBN Parsing Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md Use the 'isbn' CLI command to parse, convert, and format ISBNs. Supports various output formats. ```bash isbn [format] ``` ```bash isbn 978-4-87311-336-4 13h # ISBN-13 with hyphens isbn 978-4-87311-336-4 10 # ISBN-10 without hyphens isbn 978-4-87311-336-4 data # All data as JSON ``` -------------------------------- ### Node.js CommonJS Module Import Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Shows how to import the ISBN3 library using CommonJS format in a Node.js environment. ```javascript const ISBN = require('isbn3') ``` -------------------------------- ### Stream Process ISBNs with CLI Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/audit.md Audit a newline-delimited list of ISBNs using the command-line interface. The CLI outputs only ISBNs that have associated clues, indicating potential issues. ```bash cat isbns.txt | isbn-audit > audit_results.ndjson ``` -------------------------------- ### Output ISBN Metadata as JSON Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md Retrieve all metadata for an ISBN in JSON format by using the 'data' format specifier with the 'isbn' command. ```bash isbn 978-1-4915-7431-7 data # Output: { # "source": "978-1-4915-7431-7", # "isValid": true, # ... # } ``` -------------------------------- ### Handle ISBN-10 to ISBN-13 Conversion Errors Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md If `asIsbn10()` returns null for a valid ISBN, it might be because the ISBN has a 979 prefix. In such cases, use `asIsbn13()` as a fallback. ```javascript const isbn10 = ISBN.asIsbn10(input) if (isbn10 === null) { // Use ISBN-13 instead const isbn13 = ISBN.asIsbn13(input) if (isbn13) { console.log('Using ISBN-13:', isbn13) } else { console.error('Invalid ISBN') } } ``` -------------------------------- ### Import All Exports (ES6 Modules) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/MODULE_INDEX.md Import all exports using ES6 module syntax. Requires a transpiler or Node.js 12+ with experimental modules enabled. ```javascript // Requires transpiler or Node.js 12+ with --experimental-modules import * as ISBN from 'isbn3' ``` -------------------------------- ### Convert Existing ISBN-13 to ISBN-13 (Compact) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn13.md Handles an already ISBN-13 formatted string and returns it in compact format. This demonstrates that the function works correctly even if the input is already in the target format. ```javascript const ISBN = require('isbn3') // Already ISBN-13 input const result3 = ISBN.asIsbn13('978-4-87311-336-4') // '9784873113364' ``` -------------------------------- ### StandardJS Linting Configuration Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Configuration for the StandardJS linter, specifying files to ignore and global variables. ```json "standard": { "ignore": ["dist"], "globals": ["it", "describe"] } ``` -------------------------------- ### Convert ISBN-10 to ISBN-10 (Compact) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn10.md Handles an already ISBN-10 input and returns its compact ISBN-10 representation. Requires the 'isbn3' module. ```javascript const ISBN = require('isbn3') // Already ISBN-10 input const result3 = ISBN.asIsbn10('4-87311-336-9') // '4873113369' ``` -------------------------------- ### Checking for Group Existence Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/groups.md Demonstrates how to check if a specific ISBN group prefix exists in the `groups` object before accessing its properties. This prevents errors when a group might not be present. ```javascript // Check if a group exists if (ISBN.groups['978-2']) { console.log(ISBN.groups['978-2'].name) // 'French language' } ``` -------------------------------- ### Include browserified version Source: https://github.com/inventaire/isbn3/blob/main/README.md Include the ES5 browserified version of the module in an HTML file. This exposes the ISBN module on the window object. ```html ``` -------------------------------- ### Browser Usage with Script Tag Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/configuration.md Explains how to include the browserified ISBN3 distribution via a script tag and access its functions globally. ```html ``` -------------------------------- ### Migrate Database ISBN-10 to ISBN-13 Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md A migration script to update ISBN references in a database from ISBN-10 to ISBN-13 format. It iterates through books, parses ISBNs, and updates records if necessary. ```javascript // Migrate old ISBN-10 references to ISBN-13 async function migrateDatabase() { const books = await db.collection('books').find().toArray() for (const book of books) { const parsed = ISBN.parse(book.isbn) if (parsed && parsed.isbn13 !== book.isbn) { await db.collection('books').updateOne( { _id: book._id }, { $set: { isbn: parsed.isbn13, isbn_hyphenated: parsed.isbn13h } } ) } } } ``` -------------------------------- ### npm Scripts for ISBN Validation and Normalization Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md Define npm scripts to validate ISBNs from a file, normalize them to ISBN-13 format, or run the basic isbn command. ```json { "scripts": { "validate-isbns": "cat books.txt | isbn-audit | jq '.validIsbn' | grep -c false", "normalize-isbns": "while read isbn; do isbn \"$isbn\" 13h; done < books.txt", "check-isbn": "isbn" } } ``` -------------------------------- ### Handle Numeric Input Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/parse.md Illustrates that the function can accept numeric input and will convert it to a string for parsing. ```javascript // Numeric input const result6 = ISBN.parse(9781933988037) ``` -------------------------------- ### isbn Command Usage Source: https://github.com/inventaire/isbn3/blob/main/README.md Use the 'isbn' command to format and validate ISBNs. It accepts various input formats and output formats, including JSON. ```sh isbn Valid ISBN input examples: - 9781491574317 - 978-1-4915-7431-7 - 978-1491574317 - isbn:9781491574317 - 9781-hello-491574317 - 030433376X - 0-304-33376-X Formats: - h: hyphen - n: no hyphen - 13: ISBN-13 without hyphen - 13h: ISBN-13 with hyphen (default) - 10: ISBN-10 without hyphen - 10h: ISBN-10 with hyphen - prefix, group, publisher, article, check, check10, check13: output ISBN part value - data: output all this data as JSON ``` -------------------------------- ### Handle Invalid ISBN or Conversion to ISBN-10 with asIsbn10() Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Use this snippet to convert an input to an ISBN-10 string. It returns null if the input is invalid or cannot be converted to ISBN-10 (e.g., 979-prefix). Includes a fallback to ISBN-13. ```javascript const isbn10 = ISBN.asIsbn10(input) if (isbn10 === null) { console.error('Invalid ISBN or cannot convert to ISBN-10') // Fallback to ISBN-13 const isbn13 = ISBN.asIsbn13(input) } else { console.log('ISBN-10:', isbn10) } ``` -------------------------------- ### ISBN Parsing Pipeline Flow Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/internal-modules.md Illustrates the sequence of operations in the ISBN parsing pipeline, from initial parsing to validation. ```text parse(input) ↓ normalize (remove spaces, hyphens) ↓ splitIsbnParts(value) ├→ getGroup(value) │ └→ groups lookup │ └→ returns { group, publisher, article, check } ↓ fill(codes) ├→ groups lookup (get groupname) ├→ calculateCheckDigit (for ISBN-10) ├→ calculateCheckDigit (for ISBN-13) └→ returns complete ISBN object with formatted strings ↓ validate (check digit matches) ↓ return ISBN object or null ``` -------------------------------- ### Handle Invalid ISBN Input Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn10.md Shows that invalid ISBN strings result in null when passed to asIsbn10. Requires the 'isbn3' module. ```javascript const ISBN = require('isbn3') // Invalid input const result7 = ISBN.asIsbn10('not an isbn') // null ``` -------------------------------- ### JavaScript: Handle null gracefully in formatting Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Provides a fallback string for invalid ISBN inputs when formatting. If the hyphenation fails (returns null or empty), it returns a user-friendly 'Invalid: [input]' message. ```javascript function formatIsbn(input) { const formatted = ISBN.hyphenate(input) return formatted || `Invalid: ${input}` } ``` -------------------------------- ### isbn-checksum Command Usage Source: https://github.com/inventaire/isbn3/blob/main/README.md Use the 'isbn-checksum' command to calculate the checksum for a given ISBN. It can accept an ISBN with or without a checksum, and will output the correct checksum. ```sh isbn-checksum ``` ```sh isbn-checksum 978-4-87311-336-4 # { # "input": "978-4-87311-336-4", # "checksumCalculatedFrom": "978487311336", # "checksum": "4", # "isbn": "978-4-87311-336-4" # } ``` ```sh isbn-checksum 978-4-87311-336-1 # { # "input": "978-4-87311-336-1", # "checksumCalculatedFrom": "978487311336", # "checksum": "4", # "isbn": "978-4-87311-336-4" # } ``` ```sh isbn-checksum 978-4-87311-336 # { # "input": "978-4-87311-336", # "checksumCalculatedFrom": "978487311336", # "checksum": "4", # "isbn": "978-4-87311-336-4" # } ``` ```sh isbn-checksum 978487311336 # { # "input": "978487311336", # "checksumCalculatedFrom": "978487311336", # "checksum": "4", # "isbn": "978-4-87311-336-4" # } ``` ```sh isbn-checksum 978-4-87311-336-1 ``` -------------------------------- ### Convert ISBN Formats Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md Shows how to convert ISBN strings between ISBN-13 and ISBN-10 formats. Note that conversions are not always possible. ```javascript ISBN.asIsbn13('4873113369') // '9784873113364' ISBN.asIsbn10('978-4-87311-336-4') // '4873113369' ``` -------------------------------- ### Parse and Use ISBN Data Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md Demonstrates how to parse an ISBN string, access its properties like the hyphenated ISBN-13 and group name, and handle potential null results. ```javascript const ISBN = require('isbn3') // Parse an ISBN const result = ISBN.parse('978-4-87311-336-4') if (result) { console.log(result.isbn13h) // '978-4-87311-336-4' console.log(result.groupname) // 'Japan' } ``` -------------------------------- ### Check for ISBN-10 Availability (979 Prefix) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md Identifies if an ISBN-13 has a 979 prefix, which means an ISBN-10 conversion is not possible. This check is useful before attempting such a conversion. ```javascript const isbn13h = parsed.isbn13h if (isbn13h.startsWith('979-')) { console.log('ISBN-10 not available for 979-prefix ISBNs') } ``` -------------------------------- ### Calculate checksum for complete ISBN-13 Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md Use this command to calculate the checksum for a complete ISBN-13 number. The tool will output a JSON object containing the input, the digits used for calculation, the calculated checksum, and the corrected ISBN. ```bash isbn-checksum 978-4-87311-336-4 # Output: { # "input": "978-4-87311-336-4", # "checksumCalculatedFrom": "978487311336", # "checksum": "4", # "isbn": "978-4-87311-336-4" # } ``` -------------------------------- ### Shell Script for Pipe Processing ISBNs Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/quick-start.md Process ISBNs through a pipeline to find those with potential errors using `isbn-audit` and `jq`. ```bash # Find all ISBNs with potential errors cat isbns.ndjson | \ jq -r '.isbn' | \ isbn-audit | \ jq 'select(.clues | length > 0)' ``` -------------------------------- ### Audit ISBN for Issues Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/README.md Illustrates how to use the audit function to detect errors in an ISBN string and retrieve details about potential issues. ```javascript // Audit for issues const audit = ISBN.audit('978-1-0906-4852-4') // Returns: { source, validIsbn, clues: [...] } ``` -------------------------------- ### asIsbn10(isbn, hyphen) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn10.md Converts an ISBN to its ISBN-10 representation. Returns null if the ISBN is invalid or cannot be represented as ISBN-10 (e.g., 979-prefix ISBNs). ```APIDOC ## asIsbn10(isbn, hyphen) ### Description Converts an ISBN (ISBN-10 or ISBN-13) to its ISBN-10 representation. It handles both hyphenated and compact formats and returns null for invalid or unconvertible ISBNs. ### Signature ```javascript asIsbn10(isbn: string | number, hyphen?: boolean): string | null ``` ### Parameters #### Parameters - **isbn** (string or number) - Required - The ISBN to convert (ISBN-10 or ISBN-13). - **hyphen** (boolean) - Optional - If true, returns the hyphenated format; if false, returns the compact format. Defaults to false. ### Return Type Returns a string containing the 10-digit ISBN, or `null` if the input ISBN is invalid or cannot be converted to ISBN-10. ### Behavior - Parses the input using the `parse()` function. - Returns null if parsing fails or if the parsed ISBN has no `isbn10` field (e.g., 979-prefixed ISBNs). - Returns the `isbn10h` field if `hyphen` is true. - Returns the `isbn10` field if `hyphen` is false. - Only 978-prefixed ISBNs can be converted to ISBN-10. ### Examples ```javascript const ISBN = require('isbn3') // Convert to ISBN-10 without hyphen (default) const result1 = ISBN.asIsbn10('978-4-87311-336-4') // '4873113369' // Convert to ISBN-10 with hyphen const result2 = ISBN.asIsbn10('978-4-87311-336-4', true) // '4-87311-336-9' // Already ISBN-10 input const result3 = ISBN.asIsbn10('4-87311-336-9') // '4873113369' // ISBN-10 input with hyphen output const result4 = ISBN.asIsbn10('4-87311-336-9', true) // '4-87311-336-9' // 979-prefix ISBN (cannot convert to ISBN-10) const result5 = ISBN.asIsbn10('979-10-96908-02-8') // null // 979-prefix with hyphen param const result6 = ISBN.asIsbn10('979-10-96908-02-8', true) // null // Invalid input const result7 = ISBN.asIsbn10('not an isbn') // null ``` ``` -------------------------------- ### parse(isbn) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/MODULE_INDEX.md Main parsing function; validates and normalizes ISBN. It takes a string or number representing an ISBN and returns an ISBN object or null if parsing fails. ```APIDOC ## parse(isbn) ### Description Main parsing function; validates and normalizes ISBN. It takes a string or number representing an ISBN and returns an ISBN object or null if parsing fails. ### Signature ```javascript parse(isbn: string | number): ISBN | null ``` ### Purpose Validates and normalizes ISBN input. ``` -------------------------------- ### Quality Assurance Pipeline for ISBNs Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md This script pipes ISBNs from a file through `isbn-audit` and then uses `jq` to filter and format output, selecting entries that are either invalid ISBNs or have quality clues. It extracts the source, the first clue's message, and a suggested ISBN-13h. ```bash # Check ISBNs for data quality issues cat raw_isbns.txt | isbn-audit | jq 'select(.validIsbn == false or (.clues | length > 0)) | { source, issue: .clues[0].message, suggestion: .clues[0].candidate.isbn13h }' ``` -------------------------------- ### JavaScript: Use clues for user feedback Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Checks the audit result for validation errors and clues. If an ISBN is invalid and clues are available, it logs the first clue's message and a suggested candidate ISBN. ```javascript const audit = ISBN.audit(input) if (!audit.validIsbn && audit.clues.length > 0) { const suggestion = audit.clues[0] console.log(`Error: ${suggestion.message}`) if (suggestion.candidate) { console.log(`Try: ${suggestion.candidate.isbn13h}`) } } ``` -------------------------------- ### Audit ISBNs from File and Save Results Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md Read ISBNs from a file, pipe them to `isbn-audit`, and redirect the JSON output to a new file named `audit_results.ndjson`. This is suitable for saving audit results for later analysis. ```bash # Audit file and save results cat isbns.txt | isbn-audit > audit_results.ndjson ``` -------------------------------- ### ISBN.asIsbn10(isbn, hyphen) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Converts a given ISBN to its ISBN-10 string representation. Returns null if the input cannot be parsed or converted to ISBN-10. ```APIDOC ## ISBN.asIsbn10(isbn, hyphen) ### Description Converts a given ISBN to its ISBN-10 string representation. Returns null if the input cannot be parsed or converted to ISBN-10. ### Return value `string | null` ### Null Cases - `parse()` returns null for the input - Parsed ISBN has no ISBN-10 equivalent (e.g., 979-prefix) ### Handling ```javascript const isbn10 = ISBN.asIsbn10(input) if (isbn10 === null) { console.error('Invalid ISBN or cannot convert to ISBN-10') // Fallback to ISBN-13 const isbn13 = ISBN.asIsbn13(input) } else { console.log('ISBN-10:', isbn10) } ``` ``` -------------------------------- ### Validate Input Before Calling audit() Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md This snippet demonstrates pre-validation of input before calling ISBN.audit() to prevent errors related to non-string or empty string inputs. It ensures the input is a non-empty string. ```javascript // Validate before calling audit() if (typeof input !== 'string' || input.length === 0) { console.error('Invalid input: must be non-empty string') return } const result = ISBN.audit(input) ``` -------------------------------- ### Handle Invalid ISBN Input (Compact) Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/api-reference/asIsbn13.md Demonstrates that the function returns null when provided with an invalid ISBN string and the hyphen parameter is not specified. ```javascript const ISBN = require('isbn3') // Invalid input const result7 = ISBN.asIsbn13('not an isbn') // null ``` -------------------------------- ### asIsbn10(isbn: string, hyphen?: boolean): string | null Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/types.md Converts an ISBN string to its ISBN-10 representation. Optionally retains hyphens. ```APIDOC ## asIsbn10(isbn: string, hyphen?: boolean): string | null ### Description Converts an ISBN string to its ISBN-10 representation. Optionally retains hyphens. ### Method `asIsbn10` ### Parameters #### Path Parameters - **isbn** (string) - Required - The ISBN string to convert. - **hyphen** (boolean) - Optional - If true, the returned ISBN-10 will include hyphens. ### Response #### Success Response (string | null) - Returns the ISBN-10 string if conversion is successful, otherwise returns `null`. ### Response Example ```json "0-321-76572-3" ``` ``` -------------------------------- ### Audit-First Approach for ISBN Validation Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md This snippet demonstrates an audit-first approach to ISBN validation, logging whether the ISBN is valid, its group name, and any identified issues or clues. ```javascript const audit = ISBN.audit(input) console.log({ valid: audit.validIsbn, group: audit.groupname, issues: audit.clues.map(c => c.message) }) ``` -------------------------------- ### JavaScript: Wrap audit() in try-catch Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md Wraps the ISBN audit function in a try-catch block to handle potential errors during the audit process. Logs an error message and returns null if an exception occurs. ```javascript function auditIsbn(input) { try { return ISBN.audit(input) } catch (error) { console.error('Invalid input for audit:', input) return null } } ``` -------------------------------- ### Audit ISBNs from Stdin Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md Pipe a list of newline-delimited ISBNs to the `isbn-audit` command via standard input for batch processing. This is useful for auditing multiple ISBNs at once. ```bash # Audit from stdin (newline-delimited ISBNs) echo ' 9784873113364 9781090648525 978-1-0906-4852-4 ' | isbn-audit ``` -------------------------------- ### asIsbn13(isbn: string, hyphen?: boolean): string | null Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/types.md Converts an ISBN string to its ISBN-13 representation. Optionally retains hyphens. ```APIDOC ## asIsbn13(isbn: string, hyphen?: boolean): string | null ### Description Converts an ISBN string to its ISBN-13 representation. Optionally retains hyphens. ### Method `asIsbn13` ### Parameters #### Path Parameters - **isbn** (string) - Required - The ISBN string to convert. - **hyphen** (boolean) - Optional - If true, the returned ISBN-13 will include hyphens. ### Response #### Success Response (string | null) - Returns the ISBN-13 string if conversion is successful, otherwise returns `null`. ### Response Example ```json "978-0-321-76572-3" ``` ``` -------------------------------- ### Convert ISBN-13 to ISBN-10 with Hyphens Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/endpoints.md Convert a hyphenated ISBN-13 to a hyphenated ISBN-10 using the 'isbn' command and specifying the '10h' format. ```bash isbn 978-1-4915-7431-7 10h # Output: 0-304-33376-1 ``` -------------------------------- ### Handle Invalid ISBN with asIsbn13() Source: https://github.com/inventaire/isbn3/blob/main/_autodocs/errors.md This snippet demonstrates how to convert an input to an ISBN-13 string, returning null if the input is not a valid ISBN. It checks for null returns from ISBN.asIsbn13(). ```javascript const isbn13 = ISBN.asIsbn13(input) if (isbn13 === null) { console.error('Invalid ISBN') } else { console.log('ISBN-13:', isbn13) } ```