npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@j_c/sea-cat-chain_astro-openapi--validation

v0.7.0

Published

Provides useful code generation for where you need to pass serializabled data. Very useful for:

Downloads

15

Readme

Astro OpenAPI — JSON Schema helpers (runtime checks, types…)

Provides useful code generation for where you need to pass serializabled data.
Very useful for:

  • User input (Form, API request…)
  • Markdown Frontmatter data
  • Environment sourced variables (.env, Docker, JS configs…)

Features

  • Runtime validation
  • Precise error reporting
  • Static types
  • TS Documentation (auto-completion goodness).
  • Replace missing / wrong content with fake / default / example.

Installation

pnpm astro add @astro-content/validator

OR

pnpm i @astro-content/validator, then add to your astro.config.mjs:

import contentValidator from '@astro-content/validator';

export default defineConfig({
	// ...
	integrations: [
		//...
		contentValidator({ outDir: 'src/checkers' }),
	],
});

OR

Shallow clone demo project:

pnpx degit JulianCataldo/astro-content/packages/validator/demo ./ac-validator-demo

Integration

It will scan all src/**/*.schema.yaml in the Astro project and generate associated runtime validator and static types.

Settings:

  • outDir: Central destination for the generated checkers. Default: None
    Examples: src/checkers, .astro-content/checkers, .astro/checkers

If you leave it blank, generated files will be colocated with their input schema, regardless of their containing directory (a bit like a TypeScript declaration file). E.g. ./src/schemas/post.schema.yaml./src/schemas/post.checker.ts

Usage

Gist:

import { checkArticle } from '/src/checkers/article.checker';

const frontmatter = { title: 'Hello world' };

const { result: entry, errors } = await checkArticle(frontmatter);

console.log({ title: entry.title, errors });

if (errors) {
	// We don't want to pursue…
}
// Or maybe we want to!
// E.g. You've set the `default` or `examples` fields as fallbacks,
// or you'll get valid, though fake data.

See also .remarkrc.yaml, wrong_entry-foo.md, blog-post.schema.yaml.


In Astro templates:

---
import { Code } from 'astro/components';
import { checkBlogPost } from '../checkers/blog-post.checker';

// Pre-validate all data upfront. This is not always wanted.
const blogPosts = await Astro.glob('/content/blog-posts/*.md').then((posts) =>
	Promise.all(posts.map((post) => checkBlogPost(post.frontmatter))),
);

console.log(blogPosts);
---

<Code code={JSON.stringify(blogPosts, null, 2)} lang={'json'} />


[
	{
		"result": {
			"title": "This is a cool title.",
			"description": "My description is long enough to make the schema happy.\nMore text. More text. More text. More text. More text.\n"
		},
		"schema": {
			// ...
		}
	},
	{
		"result": {
			"title": "My untitled blog post",
			"tags": ["Music"],
			"description": "No description found."
		},
		"errors": [
			{
				"instancePath": "/tags/0",
				"schemaPath": "#/allOf/0/properties/tags/items/type",
				"keyword": "type",
				"params": {
					"type": "string"
				},
				"message": "must be string"
			},
			{
				"instancePath": "/tags/0",
				"schemaPath": "#/allOf/0/properties/tags/items/enum",
				"keyword": "enum",
				"params": {
					"allowedValues": [
						"Music",
						"Video",
						"Development",
						"Cooking",
						"Gardening",
						"Sport"
					]
				},
				"message": "must be equal to one of the allowed values"
			},
			{
				"instancePath": "",
				"schemaPath": "#/allOf/1/required",
				"keyword": "required",
				"params": {
					"missingProperty": "description"
				},
				"message": "must have required property 'description'"
			},
			{
				"instancePath": "/title",
				"schemaPath": "#/allOf/1/properties/title/type",
				"keyword": "type",
				"params": {
					"type": "string"
				},
				"message": "must be string"
			}
		],
		"original": {
			"title": 123456,
			"tags": [123456]
		},
		"schema": {
			// ...
		}
	}
]

See also the demo project to play with.

Alternative methods for generating checkers

This library is thought primarly as an Astro project integration but in fact, you could use it with any JS / TS project of yours, and use the helpers in the browser, too.

Moreover, you might want to customize checker generation inside your workflow.
You can access these helpers with an API and the CLI too.

API

import { generateChecker, generateAllCheckers } from './schema-to-validator';

const outDir = 'src/checkers';
await generateAllCheckers(outDir);

const schemaPath = 'src/schemas/post.schema.yaml';
await generateChecker(schemaPath, outDir);

Recommendations

For the best experience, use these helpers in combination with remark-lint-frontmatter-schema.

Why JSON Schema (w. AJV)?

But really, the two main reasons are that:

  1. AFAIK, it's the only way to get your hard worked-on TSDoc (from description field). Which means nice and insightful auto-completion.
  2. It allows this lib. to integrate perfectly with remark-lint-frontmatter-schema. This way, you get an end-to-end schema + types validation experience, from sources to client browser.

Ideas

  • Refine the way on how fallback data is injected, relating to error handling and user preferences.

🔗  JulianCataldo.com