CodeSampleX

サンプル

marked 18.0.5: Hooks

検証済みサンプル — npm marked 18.0.5: Hooks. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: marked.Hooks is exported as a class with passThroughHooks…

sha256:8f3ad9c169011e92f2623b9f96c0ce35355a93edfaa06eeadb6543db868c5cf5

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
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

ケース

HOW
ゴール
verify marked.Hooks in pkg:npm/marked@18.0.5
パッケージ
シンボル
  • marked.Hooks
作成日
2026-08-28T00:00:37Z

コントラクト

  1. marked.Hooks is exported as a class with passThroughHooks and prototype methods
  2. marked.Hooks instance provides default pass-through implementations for preprocess, postprocess, and processAllTokens
  3. marked.Hooks provideLexer and provideParser return lexer and parser functions for block and inline modes
  4. marked.Hooks preprocess, processAllTokens, and postprocess hooks transform markdown, tokens, and HTML output
  5. marked.Marked chains multiple hooks registered via use in sequence

ファイル

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

ソースアーティファクトをダウンロード (tar.gz)

ソース

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: verify marked.Hooks in pkg:npm/marked@18.0.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/marked@18.0.5
Demonstrate these symbols/APIs:
  - marked.Hooks

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:80fef6ad0638171404ac6fcc99b3db086cb96dfeae41c80ea26c899f21c74ef3","contract":["marked.Hooks is exported as a class with passThroughHooks and prototype methods","marked.Hooks instance provides default pass-through implementations for preprocess, postprocess, and processAllTokens","marked.Hooks provideLexer and provideParser return lexer and parser functions for block and inline modes","marked.Hooks preprocess, processAllTokens, and postprocess hooks transform markdown, tokens, and HTML output","marked.Marked chains multiple hooks registered via use in sequence"],"goal":"verify marked.Hooks in pkg:npm/marked@18.0.5","kind":"HOW","packages":["pkg:npm/marked@18.0.5"],"schemaVersion":1,"symbols":["marked.Hooks"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/marked@18.0.5"],"schemaVersion":1,"subject":"pkg:npm/marked@18.0.5","symbols":["marked.Hooks"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-marked-hooks",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-marked-hooks",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "marked": "18.0.5"
      }
    },
    "node_modules/marked": {
      "version": "18.0.5",
      "resolved": "https://registry.npmjs.org/marked/-/marked-18.0.5.tgz",
      "integrity": "sha512-S6GcvALHg6K4ohtu4E7x0a1AqhAjp6cV8KhLSyN9qVapnzJkusVBxZRcIU9AeYsbe6P1hKDusSbEOzGyyuce6w==",
      "license": "MIT",
      "bin": {
        "marked": "bin/marked.js"
      },
      "engines": {
        "node": ">= 20"
      }
    }
  }
}
package.json
{
  "name": "sample-marked-hooks",
  "version": "1.0.0",
  "private": true,
  "license": "MIT-0",
  "main": "src/index.js",
  "dependencies": {
    "marked": "18.0.5"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify marked.Hooks in pkg:npm/marked@18.0.5",
  "kind": "HOW",
  "packages": [
    "pkg:npm/marked@18.0.5"
  ],
  "symbols": [
    "marked.Hooks"
  ]
}
src/index.js
const { marked, Marked, Hooks } = require('marked');

/**
 * Creates an instance of marked.Hooks with optional configuration.
 *
 * @param {object} [options] - Configuration options for Hooks.
 * @returns {Hooks} Instance of marked.Hooks.
 */
function createHooks(options) {
  return new Hooks(options);
}

/**
 * Creates custom hooks definition object that demonstrates preprocessing,
 * token processing, and postprocessing.
 *
 * @param {object} [transforms] - Custom transform functions.
 * @returns {object} Hooks object compatible with marked.use.
 */
function createCustomHooks({
  variableReplacements = {},
  uppercaseHeadings = false,
  wrapperElement = null
} = {}) {
  return {
    preprocess(markdown) {
      let result = markdown;
      for (const [key, value] of Object.entries(variableReplacements)) {
        result = result.replaceAll(`{{${key}}}`, value);
      }
      return result;
    },
    processAllTokens(tokens) {
      if (uppercaseHeadings) {
        for (const token of tokens) {
          if (token.type === 'heading' && token.tokens) {
            token.tokens.forEach((child) => {
              if (child.type === 'text') {
                child.text = child.text.toUpperCase();
              }
            });
          }
        }
      }
      return tokens;
    },
    postprocess(html) {
      if (wrapperElement) {
        return `<${wrapperElement}>\n${html.trim()}\n</${wrapperElement}>`;
      }
      return html;
    }
  };
}

/**
 * Creates a Marked instance configured with specified hooks.
 *
 * @param {object} hooks - Hooks object or configuration.
 * @param {object} [options] - Additional marked options.
 * @returns {Marked} Configured Marked instance.
 */
function createMarkedWithHooks(hooks, options = {}) {
  const instance = new Marked(options);
  instance.use({ hooks });
  return instance;
}

module.exports = {
  Hooks,
  createHooks,
  createCustomHooks,
  createMarkedWithHooks
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const markedModule = require('marked');
const {
  Hooks,
  createHooks,
  createCustomHooks,
  createMarkedWithHooks
} = require('../src/index.js');

// 1. Verify marked.Hooks export and static properties
assert.equal(typeof Hooks, 'function', 'Hooks must be a constructor function/class');
assert.strictEqual(Hooks, markedModule.Hooks, 'Hooks export must match marked.Hooks');
assert.ok(Hooks.passThroughHooks instanceof Set, 'Hooks.passThroughHooks must be a Set');
assert.ok(Hooks.passThroughHooks.has('preprocess'), 'passThroughHooks must contain preprocess');
assert.ok(Hooks.passThroughHooks.has('postprocess'), 'passThroughHooks must contain postprocess');
assert.ok(Hooks.passThroughHooks.has('processAllTokens'), 'passThroughHooks must contain processAllTokens');
assert.ok(Hooks.passThroughHooksRespectAsync instanceof Set, 'Hooks.passThroughHooksRespectAsync must be a Set');

// 2. Verify default Hooks prototype methods and pass-through behavior
assert.equal(typeof Hooks.prototype.preprocess, 'function', 'Hooks.prototype.preprocess must be a function');
assert.equal(typeof Hooks.prototype.postprocess, 'function', 'Hooks.prototype.postprocess must be a function');
assert.equal(typeof Hooks.prototype.processAllTokens, 'function', 'Hooks.prototype.processAllTokens must be a function');
assert.equal(typeof Hooks.prototype.provideLexer, 'function', 'Hooks.prototype.provideLexer must be a function');
assert.equal(typeof Hooks.prototype.provideParser, 'function', 'Hooks.prototype.provideParser must be a function');

const defaultHooks = createHooks();
assert.equal(defaultHooks.preprocess('# Raw Markdown'), '# Raw Markdown', 'Default preprocess must return markdown unchanged');
assert.equal(defaultHooks.postprocess('<h1>Raw HTML</h1>'), '<h1>Raw HTML</h1>', 'Default postprocess must return HTML unchanged');

const sampleTokens = markedModule.lexer('# Sample Title');
const returnedTokens = defaultHooks.processAllTokens(sampleTokens);
assert.strictEqual(returnedTokens, sampleTokens, 'Default processAllTokens must return tokens array unchanged');

// 3. Verify provideLexer and provideParser execution
const blockLexer = defaultHooks.provideLexer(true);
const inlineLexer = defaultHooks.provideLexer(false);
const blockParser = defaultHooks.provideParser(true);
const inlineParser = defaultHooks.provideParser(false);

assert.equal(typeof blockLexer, 'function', 'provideLexer(true) must return block lexer function');
assert.equal(typeof inlineLexer, 'function', 'provideLexer(false) must return inline lexer function');
assert.equal(typeof blockParser, 'function', 'provideParser(true) must return block parser function');
assert.equal(typeof inlineParser, 'function', 'provideParser(false) must return inline parser function');

const parsedFromLexer = blockParser(blockLexer('# Block Title'));
assert.ok(parsedFromLexer.includes('<h1>Block Title</h1>'), 'blockParser must parse block tokens into HTML');

const parsedInline = inlineParser(inlineLexer('**bold text**'));
assert.ok(parsedInline.includes('<strong>bold text</strong>'), 'inlineParser must parse inline tokens into HTML');

// 4. Verify custom hooks execution in Marked parsing pipeline
const customHooks = createCustomHooks({
  variableReplacements: { name: 'CodeSampleX', version: '18.0.5' },
  uppercaseHeadings: true,
  wrapperElement: 'article'
});

const markedInstance = createMarkedWithHooks(customHooks);
const inputMarkdown = '# welcome to {{name}}\n\nRunning version {{version}}.';
const renderedHtml = markedInstance.parse(inputMarkdown);

assert.equal(typeof renderedHtml, 'string', 'marked.parse with hooks must return HTML string');
assert.ok(renderedHtml.startsWith('<article>'), 'postprocess hook must wrap HTML with opening tag');
assert.ok(renderedHtml.endsWith('</article>'), 'postprocess hook must wrap HTML with closing tag');
assert.ok(renderedHtml.includes('<h1>WELCOME TO CODESAMPLEX</h1>'), 'processAllTokens and preprocess hooks must transform heading text');
assert.ok(renderedHtml.includes('<p>Running version 18.0.5.</p>'), 'preprocess hook must interpolate variables in paragraph');

// 5. Verify multiple hooks chaining via marked.use
const chainedInstance = new markedModule.Marked();
chainedInstance.use({
  hooks: {
    preprocess(src) {
      return src + ' [Hook 1]';
    }
  }
});
chainedInstance.use({
  hooks: {
    preprocess(src) {
      return src + ' [Hook 2]';
    },
    postprocess(html) {
      return html.trim() + '\n<!-- verified -->';
    }
  }
});

const chainedResult = chainedInstance.parse('Document content');
assert.ok(chainedResult.includes('Document content [Hook 2] [Hook 1]'), 'Chained preprocess hooks must compose correctly');
assert.ok(chainedResult.endsWith('<!-- verified -->'), 'Chained postprocess hook must execute');

console.log('Contract tests passed successfully.');

オリジンシーダー

匿名