Compare commits

...

12 commits
v0.4.5 ... main

26 changed files with 7293 additions and 1137 deletions

2
.husky/pre-commit Normal file
View file

@ -0,0 +1,2 @@
echo "pre-commit..."
npm run lint:fix

6
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,6 @@
{
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
}

View file

@ -1,13 +1,10 @@
> [!NOTE]
> This project moved to [SourceHut](https://git.sr.ht/~ayoayco/astro-resume).
# Astro Resume
[![Package information: NPM version](https://img.shields.io/npm/v/@ayco/astro-resume)](https://www.npmjs.com/package/@ayco/astro-resume)
[![Package information: NPM license](https://img.shields.io/npm/l/@ayco/astro-resume)](https://www.npmjs.com/package/@ayco/astro-resume)
[![Package information: NPM downloads](https://img.shields.io/npm/dt/@ayco/astro-resume)](https://www.npmjs.com/package/@ayco/astro-resume)
Utilities for serializing data from server for use in the client.
Utilities for serializing data from the server for use in the client.
1. `Serialize` - Astro component that takes `id` and `data`
1. `deserialize()` - a function for use in the client that takes an `id` string and returns the `data` object
@ -106,6 +103,7 @@ If you have shared data that needs to be initialized from the server and accesse
In this example, an appConfig object is built and serialized in index.astro and accessed in child Astro components.
In index.astro:
```astro
import Serialize from "@ayco/astro-resume";
@ -120,6 +118,7 @@ export type AppConfig = typeof appConfig;
```
In Child.astro:
```astro
<h1>I'm a child. I have access to the appConfig in index!</h1>
<GrandChild />
@ -133,6 +132,7 @@ const data = deserialize<AppConfig>('app-config');
```
In GrandChild.astro:
```astro
<h1>I'm a grand child. I also have access to the appConfig in index!</h1>
<script>
@ -177,18 +177,19 @@ console.log(now instanceof Date); // true
## Errors & Warning in `deserialize()`
The `deserialize()` function may give you the following:
1. **ERR: No match found** - there are no `JSON` scripts with the given ID
1. **WARNING: Multiple matches for <id>** - there were multiple `JSON` scripts found with the same ID
## About
This is a quick and easy pattern to embed serialized information into your HTML and make it available in the client-side script with type safety.
This is a quick and easy pattern to embed serialized information into your HTML and make it available in the client-side script. This doesn't require client-side JS and directly embeds the data on your HTML.
The `Serialize` component will write the data as JSON wrapped in a `<script type="application/json">` element to hold the string.
The `deserialize()` function can then parse the value string for use in your client script.
There is also a pattern [given in the Astro docs](https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts) to use a Custom Element that takes a `data-` prop which properly protects the scope of your component. That is a good pattern to follow for complex applications that don't use UI frameworks.
There is also a pattern [given in the Astro docs](https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts) to use a Custom Element that takes a `data-` prop which properly protects the scope of your component. It requires client-side JS.
## Trade-Off

View file

@ -1,6 +0,0 @@
import { defineConfig } from 'astro/config';
// https://astro.build/config
export default defineConfig({
output: "server",
});

43
demo/README.md Normal file
View file

@ -0,0 +1,43 @@
# Astro Starter Kit: Minimal
```sh
npm create astro@latest -- --template minimal
```
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
## 🚀 Project Structure
Inside of your Astro project, you'll see the following folders and files:
```text
/
├── public/
├── src/
│ └── pages/
│ └── index.astro
└── package.json
```
Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
Any static assets, like images, can be placed in the `public/` directory.
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).

6
demo/astro.config.mjs Normal file
View file

@ -0,0 +1,6 @@
import { defineConfig } from 'astro/config'
// https://astro.build/config
export default defineConfig({
output: 'static'
})

4723
demo/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

18
demo/package.json Normal file
View file

@ -0,0 +1,18 @@
{
"name": "demo",
"type": "module",
"version": "0.0.1",
"engines": {
"node": ">=22.12.0"
},
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@ayco/astro-resume": "workspace:*",
"astro": "^6.1.3"
}
}

View file

Before

Width:  |  Height:  |  Size: 749 B

After

Width:  |  Height:  |  Size: 749 B

View file

View file

@ -0,0 +1,44 @@
---
import Serialize from "@ayco/astro-resume";
import { stringify } from "devalue";
const data = {
nameStr: "John Doe",
isOkayBool: true,
moodNull: null,
nowDate: new Date(),
ageBigInt: BigInt("3218378192378"),
};
export type Data = typeof data;
---
<div id="render-here"></div>
<Serialize data={data} id="my-data" use={stringify} />
<script>
import { deserialize } from '@ayco/astro-resume'
import { parse } from 'devalue'
import type { Data } from './index.astro'
const data = deserialize<Data>('my-data', parse)
console.log(data)
Object.keys(data).forEach((key) =>
console.log(key, data[key], typeof data[key])
)
// render table to render-here
const table = document.createElement('table')
const tbody = document.createElement('tbody')
table.appendChild(tbody)
Object.keys(data).forEach((key) => {
const tr = document.createElement('tr')
const tdKey = document.createElement('td')
const tdValue = document.createElement('td')
tdKey.textContent = key
tdValue.textContent = data[key]
tr.appendChild(tdKey)
tr.appendChild(tdValue)
tbody.appendChild(tr)
})
document.getElementById('render-here').appendChild(table)
</script>

5
demo/tsconfig.json Normal file
View file

@ -0,0 +1,5 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

66
eslint.config.js Normal file
View file

@ -0,0 +1,66 @@
// @ts-check
import js from '@eslint/js'
import css from '@eslint/css'
import globals from 'globals'
import { defineConfig, globalIgnores } from 'eslint/config'
import stylistic from '@stylistic/eslint-plugin'
import eslintPluginAstro from 'eslint-plugin-astro'
import astroParser from 'astro-eslint-parser'
import tseslint from 'typescript-eslint'
export default defineConfig([
{
files: ['**/*.css'],
plugins: {
css
},
languageOptions: {
tolerant: true
},
language: 'css/css',
rules: {
'css/no-duplicate-imports': 'error',
'css/no-empty-blocks': 'error',
'css/no-invalid-at-rules': 'error',
'css/no-invalid-properties': 'error'
}
},
{
files: ['**/*.{js,mjs,cjs}'],
plugins: {
js, '@stylistic': stylistic
},
extends: ['js/recommended'],
languageOptions: {
globals: globals.browser
},
rules: {
'@stylistic/indent': ['error', 2],
'@stylistic/quotes': ['error', 'single'],
'@stylistic/semi': ['error', 'never'],
'@stylistic/comma-dangle': ['error', 'never'] ,
'@stylistic/block-spacing': 'error',
'@stylistic/array-bracket-spacing': ['error', 'never'],
'@stylistic/object-curly-spacing': ['error', 'always'],
'@stylistic/key-spacing': ['error', {
'beforeColon': false
}],
'@stylistic/array-bracket-newline': ['error', 'consistent'],
'@stylistic/object-curly-newline': ['error', {
'consistent': true
}]
}
},
...eslintPluginAstro.configs.recommended,
{
files: ['**/*.astro'],
languageOptions: {
parser: astroParser,
parserOptions: {
parser: tseslint.parser
}
}
},
globalIgnores(['**/dist', '**/**.d.ts'])
])

View file

@ -1,5 +0,0 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import Serialize from './src/Serialize.astro';
export default Serialize;
export * from './src/deserialize';

View file

@ -1,42 +1,27 @@
{
"name": "@ayco/astro-resume",
"author": "Ayo Ayco",
"homepage": "https://ayco.io/n/astro-resume",
"repository": {
"type": "git",
"url": "https://github.com/ayo-run/astro-resume"
},
"name": "monorepo",
"version": "0.0.1",
"private": true,
"type": "module",
"version": "0.4.5",
"keywords": [
"astro-component",
"css",
"ui"
],
"license": "MIT",
"exports": {
".": "./index.ts"
},
"files": [
"src/Serialize.astro",
"src/deserialize.ts",
"index.ts"
],
"author": "Ayo Ayco",
"scripts": {
"astro": "astro",
"dev": "astro telemetry disable && astro dev",
"start": "astro telemetry disable && astro dev",
"build": "astro telemetry disable && astro build",
"preview": "astro preview",
"publish:patch": "npm version patch && npm publish --access public",
"publish:minor": "npm version minor && npm publish --access public",
"prepare": "husky"
"dev": "cd demo && npm run dev",
"prepare": "husky",
"lint": "eslint .",
"lint:fix": "eslint . --fix"
},
"devDependencies": {
"devalue": "^5.1.1",
"husky": "^9.1.7"
},
"peerDependencies": {
"astro": "^5"
"@ayco/astro-resume": "workspace:*",
"@eslint/css": "^1.1.0",
"@eslint/js": "^10.0.1",
"@stylistic/eslint-plugin": "^5.10.0",
"astro-eslint-parser": "^1.4.0",
"bumpp": "^11.0.1",
"devalue": "^5.6.4",
"eslint": "^10.2.0",
"eslint-plugin-astro": "^1.6.0",
"globals": "^17.4.0",
"husky": "^9.1.7",
"typescript-eslint": "^8.58.0"
}
}

21
package/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 Astro Reactive
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

208
package/README.md Normal file
View file

@ -0,0 +1,208 @@
# Astro Resume
[![Package information: NPM version](https://img.shields.io/npm/v/@ayco/astro-resume)](https://www.npmjs.com/package/@ayco/astro-resume)
[![Package information: NPM license](https://img.shields.io/npm/l/@ayco/astro-resume)](https://www.npmjs.com/package/@ayco/astro-resume)
[![Package information: NPM downloads](https://img.shields.io/npm/dt/@ayco/astro-resume)](https://www.npmjs.com/package/@ayco/astro-resume)
Utilities for serializing data from the server for use in the client.
1. `Serialize` - Astro component that takes `id` and `data`
1. `deserialize()` - a function for use in the client that takes an `id` string and returns the `data` object
## Install via npm
On your [Astro](https://astro.build) project:
```
npm i @ayco/astro-resume
```
## Usage
Serializing and deserializing basic primitive data
```astro
---
import Serialize from "@ayco/astro-resume";
const data = {
hello: 'world',
}
---
<Serialize id="my-data" data={data} />
<script>
import {deserialize} from '@ayco/astro-resume';
const data = deserialize('my-data');
console.log(data) // {hello: 'world'}
</script>
```
## Type Safety
You can define a type for the data and use it in the client script.
```astro
---
import Serialize from "@ayco/astro-resume";
const data = {
hello: 'world',
isOkay: true
}
// define the type of data to be serialized
export type Data = typeof data;
---
<Serialize id="my-data" data={data} />
<script>
import {deserialize} from '@ayco/astro-resume';
/**
* reuse the type in the client
* assuming this component's name is `ThisComponent.astro`
*/
import type {Data} from './ThisComponent.astro';
const data = deserialize<Data>('my-data');
console.log(data) // {hello: 'world', isOkay: true}
</script>
```
## Passing all Astro.props to client
If you need to make all the component props to the client script:
```astro
---
import Serialize from "@ayco/astro-resume";
export interface Props {
hello: string;
isOkay: boolean;
}
---
<Serialize id="preferences" data={{...Astro.props}} />
<script>
import {deserialize} from '@ayco/astro-resume';
import type {Props} from './ThisComponent.astro';
const {hello, isOkay} = deserialize<Props>('preferences');
console.log(hello, isOkay);
</script>
```
## Serialize server data once, access everywhere
If you have shared data that needs to be initialized from the server and accessed in several places on the client-side, you can use `Serialize` once and `deserialize` in any number of Astro components as long as they are in the same page.
In this example, an appConfig object is built and serialized in index.astro and accessed in child Astro components.
In index.astro:
```astro
import Serialize from "@ayco/astro-resume";
const appConfig = {
someClientSideKey: '1234hello',
}
export type AppConfig = typeof appConfig;
---
<Serialize id="app-config" data={appConfig} />
<Child />
```
In Child.astro:
```astro
<h1>I'm a child. I have access to the appConfig in index!</h1>
<GrandChild />
<script>
import {deserialize} from '@ayco/astro-resume';
import type {AppConfig} from '..pages/index.astro';
const data = deserialize<AppConfig>('app-config');
// ... do something with the app config
</script>
```
In GrandChild.astro:
```astro
<h1>I'm a grand child. I also have access to the appConfig in index!</h1>
<script>
import {deserialize} from '@ayco/astro-resume';
import type {AppConfig} from '..pages/index.astro';
const data = deserialize<AppConfig>('app-config');
// ... do something with the app config
</script>
```
## Using a custom serializer and parser
You can bring your own custom serializer/parser if you want to opt for more complex data handling.
Here's an example of serializing data that `JSON.stringify` cannot (e.g., Date or BigInt) using Rich Harris' [`devalue`](https://github.com/Rich-Harris/devalue):
```astro
---
import {stringify} from 'devalue';
import Serialize from "@ayco/astro-resume";
const data = {
now: new Date(),
age: BigInt('3218378192378')
}
export type Data = typeof data;
---
<Serialize data={data} id="my-data" use={stringify} />
<script>
import {parse} from 'devalue';
import {deserialize} from '@ayco/astro-resume';
import type {Data} from './index.astro';
const {age, now} = deserialize<Data>('my-data', parse);
console.log(typeof age); // 'bigint'
console.log(now instanceof Date); // true
</script>
```
## Errors & Warning in `deserialize()`
The `deserialize()` function may give you the following:
1. **ERR: No match found** - there are no `JSON` scripts with the given ID
1. **WARNING: Multiple matches for <id>** - there were multiple `JSON` scripts found with the same ID
## About
This is a quick and easy pattern to embed serialized information into your HTML and make it available in the client-side script with type safety.
The `Serialize` component will write the data as JSON wrapped in a `<script type="application/json">` element to hold the string.
The `deserialize()` function can then parse the value string for use in your client script.
There is also a pattern [given in the Astro docs](https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts) to use a Custom Element that takes a `data-` prop which properly protects the scope of your component. That is a good pattern to follow for complex applications that don't use UI frameworks.
## Trade-Off
Some other frameworks themselves will manage serialized information and the IDs for you, but we don't have access to this in Astro as we are not really shipping a framework to the browser.
That's nice and ideal (in my opinion), as we are aware of how the HTML is formed and what we are shipping to our users. The trade off is that we do have to manage things ourselves.
You have to manage the IDs (i.e., make sure they are unique) and understand that the `deserialize()` function will crawl the whole document incurring a minimal performance cost depending on how big your HTML is.
## Road Map
See the [TODO tracker](https://todo.sr.ht/~ayoayco/astro-resume) for planned work items.
## Reporting Issues
To report issues or request features, send a plain text email to [~ayoayco/astro-resume@todo.sr.ht](mailto:~ayoayco/astro-resume@todo.sr.ht) or file a ticket via [SourceHut](https://todo.sr.ht/~ayoayco/astro-resume)

37
package/Serialize.astro Normal file
View file

@ -0,0 +1,37 @@
---
export interface Props {
/**
* The id that the client script will pass to the `deserialize()` function
*/
id: string;
/**
* The data to be serialized and accessed in the client script with `deserialize()`
*/
data: Record<string, any>;
/**
* Custom serializer to be used
* @param data
*/
use?: (data: Record<string, any>) => string;
}
const { id, data, use } = Astro.props;
let serializedData = "{}";
try {
serializedData = use ? use(data) : JSON.stringify(data);
} catch (err) {
/**
* ERR: data is unserializable
* - You might need a custom serializer/parser for complex data
* - Usage examples in 👉 https://ayco.io/gh/astro-resume#usage
*/
throw Error(
`astro-resume ERR: Data unserializable
- You might need a custom serializer/parser for complex data
- Usage examples in 👉 https://ayco.io/gh/astro-resume#usage
`,
err,
);
}
---
<script type="application/json" id={id} set:html={serializedData} />

View file

@ -3,9 +3,9 @@
* @param id The id of the Serialize component, used to find the serialized data in the HTML
* @param parser Custom parser to be used
* @returns The deserialized JSON data
* @see Usage examples in 👉 https://git.sr.ht/~ayoayco/astro-resume#astro-resume
* @see Usage examples in 👉 https://ayco.io/gh/astro-resume#usage
**/
export function deserialize<T = any>(id: string, parser?: (serialized: string)=>any): T {
export function deserialize<T = any>(id: string, parser?: (serialized: string) => any): T {
const elements = document.querySelectorAll<HTMLScriptElement>(`script#${id}[type="application/json"]`);
if (elements?.length > 0) {
@ -19,13 +19,13 @@ export function deserialize<T = any>(id: string, parser?: (serialized: string)=>
? parser(element.textContent)
: JSON.parse(element.textContent)
}
throw Error(`astro-resume ERR: No match found.
"deserialize('${id}')" did not find any data.
Check that the following are correct:
- The Serialize component is used with correct props
- "data" prop is not undefined
- "${id}" is the "id" of the Serialize component
See examples: https://sr.ht/~ayoayco/astro-resume/#usage
See examples: https://ayco.io/gh/astro-resume#usage
Stack trace: `)
}
}

4
package/index.ts Normal file
View file

@ -0,0 +1,4 @@
// @ts-ignore
import Serialize from './Serialize.astro';
export default Serialize;
export {deserialize} from './deserialize';

31
package/package.json Normal file
View file

@ -0,0 +1,31 @@
{
"name": "@ayco/astro-resume",
"version": "0.4.6",
"author": "Ayo Ayco",
"homepage": "https://ayco.io/n/astro-resume",
"repository": {
"type": "git",
"url": "https://github.com/ayo-run/astro-resume"
},
"type": "module",
"keywords": [
"astro-component",
"css",
"ui"
],
"license": "MIT",
"exports": {
".": "./index.ts",
"./*": "./*"
},
"files": [
"Serialize.astro",
"deserialize.ts",
"index.ts",
"LICENSE",
"README.md"
],
"peerDependencies": {
"astro": "^6"
}
}

File diff suppressed because it is too large Load diff

3
pnpm-workspace.yaml Normal file
View file

@ -0,0 +1,3 @@
packages:
- "package"
- "demo"

View file

@ -1,36 +0,0 @@
---
// type Primitive = string | number | boolean | null | undefined;
export interface Props {
/**
* The id that the client script will pass to the `deserialize()` function
*/
id: string;
/**
* The data to be serialized and accessed in the client script with `deserialize()`
*/
data: Record<string, any>;
/**
* Custom serializer to be used
* @param data
*/
use?: (data: Record<string, any>) => string;
}
const {id, data, use} = Astro.props;
let serializedData = '{}'
try {
serializedData = use ? use(data) : JSON.stringify(data);
} catch(err) {
/**
* ERR: data is unserializable
* - You might need a custom serializer/parser for complex data
* - Usage examples in 👉 https://git.sr.ht/~ayoayco/astro-resume#astro-resume
*/
throw Error(`astro-resume ERR: Data unserializable
- You might need a custom serializer/parser for complex data
- Usage examples in 👉 https://git.sr.ht/~ayoayco/astro-resume#astro-resume
`, err)
}
---
<script type="application/json" id={id} set:html={serializedData}></script>

View file

@ -1,44 +0,0 @@
---
import Serialize from "../Serialize.astro";
import { stringify } from "devalue";
const data = {
nameStr: "John Doe",
isOkayBool: true,
moodNull: null,
nowDate: new Date(),
ageBigInt: BigInt("3218378192378"),
};
export type Data = typeof data;
---
<div id="render-here"></div>
<Serialize data={data} id="my-data" use={stringify} />
<script>
import { deserialize } from "../deserialize";
import { parse } from "devalue";
import type { Data } from "./index.astro";
const data = deserialize<Data>("my-data", parse);
console.log(data);
Object.keys(data).forEach((key) =>
console.log(key, data[key], typeof data[key])
);
// render table to render-here
const table = document.createElement("table");
const tbody = document.createElement("tbody");
table.appendChild(tbody);
Object.keys(data).forEach((key) => {
const tr = document.createElement("tr");
const tdKey = document.createElement("td");
const tdValue = document.createElement("td");
tdKey.textContent = key;
tdValue.textContent = data[key];
tr.appendChild(tdKey);
tr.appendChild(tdValue);
tbody.appendChild(tr);
});
document.getElementById("render-here").appendChild(table);
</script>