CodeSampleX

Пример

luxon 3.6.1: Settings

Проверенный пример — npm luxon 3.6.1: Settings. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: Settings.defaultZone configures the…

sha256:a7a36f72525b54e56c79947a4866fe0aa04db15f93d3acd8d670b83e066a7a4e

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-27

Кейс

HOW
Цель
verify luxon.Settings in pkg:npm/luxon@3.6.1
Пакеты
Символы
  • luxon.Settings
Создан
2026-08-27T23:50:21Z

Контракт

  1. Settings.defaultZone configures the default time zone used by DateTime instances
  2. Settings.defaultLocale configures the default locale for date and time formatting
  3. Settings.now overrides the current timestamp generator used when creating new DateTime instances
  4. Settings.throwOnInvalid controls whether invalid DateTime creation throws an exception or returns an invalid object
  5. Settings.resetCaches clears internal memoized caches without error

Файлы

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

Скачать артефакт с исходным кодом (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 luxon.Settings in pkg:npm/luxon@3.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/luxon@3.6.1
Demonstrate these symbols/APIs:
  - luxon.Settings

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:177fbba072d786010fede94ee78f5d8f9857625f424f4caefe9adf3595aed43d","contract":["Settings.defaultZone configures the default time zone used by DateTime instances","Settings.defaultLocale configures the default locale for date and time formatting","Settings.now overrides the current timestamp generator used when creating new DateTime instances","Settings.throwOnInvalid controls whether invalid DateTime creation throws an exception or returns an invalid object","Settings.resetCaches clears internal memoized caches without error"],"goal":"verify luxon.Settings in pkg:npm/luxon@3.6.1","kind":"HOW","packages":["pkg:npm/luxon@3.6.1"],"schemaVersion":1,"symbols":["luxon.Settings"]},"contractCommand":["node","test/contract.js"],"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/luxon@3.6.1"],"schemaVersion":1,"subject":"pkg:npm/luxon@3.6.1","symbols":["luxon.Settings"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-luxon-settings",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-luxon-settings",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "luxon": "3.6.1"
      }
    },
    "node_modules/luxon": {
      "version": "3.6.1",
      "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.6.1.tgz",
      "integrity": "sha512-tJLxrKJhO2ukZ5z0gyjY1zPh3Rh88Ej9P7jNrZiHMUXHae1yvI2imgOZtL1TO8TW6biMMKfTtAOoEJANgtWBMQ==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    }
  }
}
package.json
{
  "name": "sample-luxon-settings",
  "version": "1.0.0",
  "private": true,
  "description": "verify luxon.Settings in pkg:npm/luxon@3.6.1",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "luxon": "3.6.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify luxon.Settings in pkg:npm/luxon@3.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/luxon@3.6.1"
  ],
  "symbols": [
    "luxon.Settings"
  ]
}
src/index.js
'use strict';

const { Settings } = require('luxon');

function setDefaultZone(zone) {
  Settings.defaultZone = zone;
}

function getDefaultZone() {
  return Settings.defaultZone;
}

function setDefaultLocale(locale) {
  Settings.defaultLocale = locale;
}

function getDefaultLocale() {
  return Settings.defaultLocale;
}

function setCustomNow(fnOrTimestamp) {
  if (typeof fnOrTimestamp === 'function') {
    Settings.now = fnOrTimestamp;
  } else {
    Settings.now = () => fnOrTimestamp;
  }
}

function resetNow() {
  Settings.now = () => Date.now();
}

function setThrowOnInvalid(throwFlag) {
  Settings.throwOnInvalid = Boolean(throwFlag);
}

function getThrowOnInvalid() {
  return Settings.throwOnInvalid;
}

function resetCaches() {
  Settings.resetCaches();
}

module.exports = {
  Settings,
  setDefaultZone,
  getDefaultZone,
  setDefaultLocale,
  getDefaultLocale,
  setCustomNow,
  resetNow,
  setThrowOnInvalid,
  getThrowOnInvalid,
  resetCaches
};
test/contract.js
'use strict';

const assert = require('node:assert');
const { Settings, DateTime } = require('luxon');
const {
  setDefaultZone,
  getDefaultZone,
  setDefaultLocale,
  getDefaultLocale,
  setCustomNow,
  resetNow,
  setThrowOnInvalid,
  getThrowOnInvalid,
  resetCaches
} = require('../src/index.js');

async function run() {
  const initialZone = Settings.defaultZone;
  const initialLocale = Settings.defaultLocale;
  const initialThrow = Settings.throwOnInvalid;

  try {
    // 1. Settings.defaultZone configures the default time zone used by DateTime instances
    Settings.defaultZone = 'utc';
    const dtUtc = DateTime.now();
    assert.strictEqual(dtUtc.zoneName, 'UTC', 'DateTime.now() should use UTC when defaultZone is utc');

    Settings.defaultZone = 'America/New_York';
    const dtNy = DateTime.fromISO('2025-06-01T12:00:00');
    assert.strictEqual(dtNy.zoneName, 'America/New_York', 'DateTime.fromISO should use defaultZone America/New_York');

    setDefaultZone('Asia/Tokyo');
    assert.strictEqual(Settings.defaultZone.name || Settings.defaultZone, 'Asia/Tokyo', 'helper setDefaultZone should update defaultZone');
    const dtTokyo = DateTime.fromISO('2025-06-01T12:00:00');
    assert.strictEqual(dtTokyo.zoneName, 'Asia/Tokyo', 'DateTime should reflect new defaultZone Asia/Tokyo');

    // 2. Settings.defaultLocale configures the default locale for date and time formatting
    Settings.defaultLocale = 'fr';
    const dtFr = DateTime.fromISO('2025-01-15');
    assert.strictEqual(dtFr.monthLong.toLowerCase(), 'janvier', 'DateTime format should use defaultLocale fr');

    setDefaultLocale('es');
    assert.strictEqual(getDefaultLocale(), 'es', 'helper getDefaultLocale should return es');
    const dtEs = DateTime.fromISO('2025-01-15');
    assert.strictEqual(dtEs.monthLong.toLowerCase(), 'enero', 'DateTime format should use defaultLocale es');

    // 3. Settings.now overrides the current timestamp generator used when creating new DateTime instances
    const fixedTimestamp = 1700000000000;
    Settings.now = () => fixedTimestamp;
    assert.strictEqual(Settings.now(), fixedTimestamp, 'Settings.now() should return custom fixed timestamp');
    const dtFixed = DateTime.now();
    assert.strictEqual(dtFixed.toMillis(), fixedTimestamp, 'DateTime.now() should return datetime at fixed timestamp');

    const anotherTimestamp = 1710000000000;
    setCustomNow(anotherTimestamp);
    assert.strictEqual(DateTime.now().toMillis(), anotherTimestamp, 'helper setCustomNow should freeze time');
    resetNow();
    assert.notStrictEqual(DateTime.now().toMillis(), anotherTimestamp, 'helper resetNow should restore live time');

    // 4. Settings.throwOnInvalid controls whether invalid DateTime creation throws an exception or returns an invalid object
    Settings.throwOnInvalid = false;
    const invalidDt = DateTime.fromISO('invalid-date-string');
    assert.strictEqual(invalidDt.isValid, false, 'Invalid DateTime should have isValid=false when throwOnInvalid is false');
    assert.strictEqual(typeof invalidDt.invalidReason, 'string', 'Invalid DateTime should have invalidReason');

    Settings.throwOnInvalid = true;
    assert.throws(
      () => {
        DateTime.fromISO('invalid-date-string');
      },
      /Invalid DateTime/,
      'DateTime.fromISO should throw when throwOnInvalid is true'
    );

    setThrowOnInvalid(false);
    assert.strictEqual(getThrowOnInvalid(), false, 'helper setThrowOnInvalid should set throwOnInvalid to false');

    // 5. Settings.resetCaches clears internal memoized caches without error
    assert.doesNotThrow(() => {
      Settings.resetCaches();
    }, 'Settings.resetCaches must execute without throwing');

    assert.doesNotThrow(() => {
      resetCaches();
    }, 'helper resetCaches must execute without throwing');

    console.log('Contract tests passed successfully.');
  } finally {
    Settings.defaultZone = initialZone;
    Settings.defaultLocale = initialLocale;
    Settings.now = () => Date.now();
    Settings.throwOnInvalid = initialThrow;
    Settings.resetCaches();
  }
}

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

Исходный сидер

аноним