CodeSampleX

Exemplo

tldts-core 7.4.10: Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup

Amostra verificada para npm tldts-core 7.4.10: Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup. O…

sha256:e81c7fb5eff167f18c4e631f6068a33d2698002e199c7975cd23e3e693deed65

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

Caso

HOW
Objetivo
Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup
Pacotes
Símbolos
  • fastPathLookup
  • getEmptyResult
  • parseImpl
  • resetResult
Ambiente
node 22.23.2
Criado
2026-08-28T09:54:59Z

Contrato

  1. getEmptyResult returns a fresh result object with all fields initialized to null
  2. resetResult resets all result fields back to null for object reuse
  3. fastPathLookup directly identifies common ICANN suffixes com, org, edu, gov, net, de when allowPrivateDomains is false
  4. fastPathLookup returns false for unhandled suffixes or when allowPrivateDomains is enabled
  5. parseImpl extracts hostname, domain, subdomain, publicSuffix and domainWithoutSuffix from URLs
  6. parseImpl detects IPv4 and IPv6 hostnames and flags them with isIp when detectIp is enabled
  7. parseImpl flags IANA special-use domain names when detectSpecialUse option is true
  8. parseImpl ignores non-string inputs and preserves the result object without throwing

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tldts-core@7.4.10
Demonstrate these symbols/APIs:
  - fastPathLookup
  - getEmptyResult
  - parseImpl
  - resetResult

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:463b86d766b36af4001b600efc78b7cfbb4c45d16d2e2552734efddc7fdbacd7","contract":["getEmptyResult returns a fresh result object with all fields initialized to null","resetResult resets all result fields back to null for object reuse","fastPathLookup directly identifies common ICANN suffixes com, org, edu, gov, net, de when allowPrivateDomains is false","fastPathLookup returns false for unhandled suffixes or when allowPrivateDomains is enabled","parseImpl extracts hostname, domain, subdomain, publicSuffix and domainWithoutSuffix from URLs","parseImpl detects IPv4 and IPv6 hostnames and flags them with isIp when detectIp is enabled","parseImpl flags IANA special-use domain names when detectSpecialUse option is true","parseImpl ignores non-string inputs and preserves the result object without throwing"],"goal":"Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup","kind":"HOW","packages":["pkg:npm/tldts-core@7.4.10"],"schemaVersion":1,"symbols":["fastPathLookup","getEmptyResult","parseImpl","resetResult"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tldts-core@7.4.10"],"schemaVersion":1,"subject":"pkg:npm/tldts-core@7.4.10","symbols":["fastPathLookup","getEmptyResult","parseImpl","resetResult"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tldts-core",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tldts-core",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tldts-core": "7.4.10"
      }
    },
    "node_modules/tldts-core": {
      "version": "7.4.10",
      "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.10.tgz",
      "integrity": "sha512-KnQjp53ZekKgm/r3l+u8kJGGzYgrWdP8+Mql7a4vijh2WE0IrZWspQj/TpTxDho/YxO+AnOZnIjQcCD+q6iJsw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-tldts-core",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for tldts-core@7.4.10",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "tldts-core": "7.4.10"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Extract hostname, domain, subdomain and public suffix using tldts-core parseImpl and fastPathLookup",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tldts-core@7.4.10"
  ],
  "symbols": [
    "fastPathLookup",
    "getEmptyResult",
    "parseImpl",
    "resetResult"
  ]
}
src/index.js
'use strict';

const {
  parseImpl,
  fastPathLookup,
  getEmptyResult,
  resetResult,
  setDefaults
} = require('tldts-core');

const FLAG = {
  HOSTNAME: 0,
  IS_VALID: 1,
  PUBLIC_SUFFIX: 2,
  DOMAIN: 3,
  SUB_DOMAIN: 4,
  ALL: 5
};

/**
 * Suffix lookup function using fastPathLookup and falling back to custom suffix rules.
 *
 * @param {string} hostname - Hostname being inspected.
 * @param {object} options - Suffix lookup options.
 * @param {object} out - Output suffix record to populate.
 */
function defaultSuffixLookup(hostname, options, out) {
  if (fastPathLookup(hostname, options, out)) {
    return;
  }
  // Custom suffix fallback for internal/custom domains
  if (hostname.endsWith('.custom')) {
    out.publicSuffix = 'custom';
    out.isIcann = false;
    out.isPrivate = true;
  }
}

/**
 * Parses a URL or hostname and extracts domain components into a result object.
 *
 * @param {string} url - Input URL or hostname string.
 * @param {object} [options] - Optional parsing options.
 * @param {function} [suffixLookup] - Suffix lookup handler.
 * @param {object} [targetResult] - Optional reusable result object.
 * @returns {object} Populated result object.
 */
function parseUrl(url, options, suffixLookup = defaultSuffixLookup, targetResult) {
  const result = targetResult || getEmptyResult();
  if (targetResult) {
    resetResult(result);
  }
  return parseImpl(url, FLAG.ALL, suffixLookup, options, result);
}

module.exports = {
  parseImpl,
  fastPathLookup,
  getEmptyResult,
  resetResult,
  setDefaults,
  FLAG,
  defaultSuffixLookup,
  parseUrl
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  parseImpl,
  fastPathLookup,
  getEmptyResult,
  resetResult,
  FLAG,
  defaultSuffixLookup,
  parseUrl
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof parseImpl, 'function', 'parseImpl must be a function');
  assert.equal(typeof fastPathLookup, 'function', 'fastPathLookup must be a function');
  assert.equal(typeof getEmptyResult, 'function', 'getEmptyResult must be a function');
  assert.equal(typeof resetResult, 'function', 'resetResult must be a function');
  assert.equal(typeof parseUrl, 'function', 'parseUrl helper must be a function');

  // 2. getEmptyResult produces fresh object with all null properties
  const fresh = getEmptyResult();
  assert.deepEqual(
    fresh,
    {
      hostname: null,
      isIp: null,
      subdomain: null,
      domain: null,
      publicSuffix: null,
      domainWithoutSuffix: null,
      isIcann: null,
      isPrivate: null,
      isSpecialUse: null
    },
    'getEmptyResult should return all-null result object'
  );

  // 3. resetResult resets mutated result back to all null
  fresh.hostname = 'test.example.com';
  fresh.domain = 'example.com';
  fresh.isIp = false;
  fresh.isIcann = true;
  resetResult(fresh);
  assert.equal(fresh.hostname, null, 'resetResult should clear hostname');
  assert.equal(fresh.domain, null, 'resetResult should clear domain');
  assert.equal(fresh.isIp, null, 'resetResult should clear isIp');
  assert.equal(fresh.isIcann, null, 'resetResult should clear isIcann');

  // 4. fastPathLookup detects common ICANN suffixes (com, org, edu, gov, net, de)
  const lookupOptions = { allowPrivateDomains: false };
  const suffixOut = { publicSuffix: null, isIcann: null, isPrivate: null };

  assert.equal(fastPathLookup('app.example.com', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'com');
  assert.equal(suffixOut.isIcann, true);
  assert.equal(suffixOut.isPrivate, false);

  assert.equal(fastPathLookup('community.example.org', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'org');

  assert.equal(fastPathLookup('portal.example.edu', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'edu');

  assert.equal(fastPathLookup('agency.example.gov', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'gov');

  assert.equal(fastPathLookup('network.example.net', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'net');

  assert.equal(fastPathLookup('site.example.de', lookupOptions, suffixOut), true);
  assert.equal(suffixOut.publicSuffix, 'de');

  // fastPathLookup returns false when allowPrivateDomains is true or suffix not in fast path
  assert.equal(fastPathLookup('app.example.com', { allowPrivateDomains: true }, suffixOut), false);
  assert.equal(fastPathLookup('site.example.custom', lookupOptions, suffixOut), false);

  // 5. parseImpl with fastPathLookup extracts hostname, subdomain, domain, publicSuffix
  const res = getEmptyResult();
  parseImpl('https://sub.blog.example.com:8080/path?query=1#hash', FLAG.ALL, defaultSuffixLookup, undefined, res);
  assert.equal(res.hostname, 'sub.blog.example.com');
  assert.equal(res.domain, 'example.com');
  assert.equal(res.subdomain, 'sub.blog');
  assert.equal(res.publicSuffix, 'com');
  assert.equal(res.domainWithoutSuffix, 'example');
  assert.equal(res.isIcann, true);
  assert.equal(res.isPrivate, false);
  assert.equal(res.isIp, false);

  // 6. parseImpl with custom fallback suffix lookup (.custom)
  resetResult(res);
  parseImpl('shop.service.custom', FLAG.ALL, defaultSuffixLookup, { extractHostname: false }, res);
  assert.equal(res.hostname, 'shop.service.custom');
  assert.equal(res.domain, 'service.custom');
  assert.equal(res.subdomain, 'shop');
  assert.equal(res.publicSuffix, 'custom');
  assert.equal(res.domainWithoutSuffix, 'service');
  assert.equal(res.isPrivate, true);

  // 7. parseImpl detects IPv4 and IPv6 addresses when detectIp is true
  resetResult(res);
  parseImpl('http://127.0.0.1:8080/api', FLAG.ALL, defaultSuffixLookup, { detectIp: true }, res);
  assert.equal(res.hostname, '127.0.0.1');
  assert.equal(res.isIp, true);
  assert.equal(res.domain, null);
  assert.equal(res.subdomain, null);

  resetResult(res);
  parseImpl('http://[::1]:3000/', FLAG.ALL, defaultSuffixLookup, { detectIp: true }, res);
  assert.equal(res.hostname, '::1');
  assert.equal(res.isIp, true);
  assert.equal(res.domain, null);

  // 8. parseImpl flags special-use domains when detectSpecialUse is true
  resetResult(res);
  parseImpl('http://localhost:3000', FLAG.ALL, defaultSuffixLookup, { detectSpecialUse: true }, res);
  assert.equal(res.hostname, 'localhost');
  assert.equal(res.isSpecialUse, true);

  // 9. parseImpl handles invalid types gracefully
  resetResult(res);
  parseImpl(null, FLAG.ALL, defaultSuffixLookup, undefined, res);
  assert.equal(res.hostname, null);

  // 10. parseUrl helper parses correctly and supports object reuse
  const reused = getEmptyResult();
  const out1 = parseUrl('https://api.example.org', undefined, defaultSuffixLookup, reused);
  assert.equal(out1, reused);
  assert.equal(reused.hostname, 'api.example.org');
  assert.equal(reused.domain, 'example.org');
  assert.equal(reused.subdomain, 'api');
  assert.equal(reused.publicSuffix, 'org');

  console.log('All tldts-core contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

Seeder de origem

anônimo