mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 02:44:45 +00:00
feat(docs): add document generator
This commit is contained in:
4
docs/.gitignore
vendored
Normal file
4
docs/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
.nuxt/
|
||||
.output/
|
||||
node_modules/
|
||||
dist/
|
||||
5
docs/app/app.vue
Normal file
5
docs/app/app.vue
Normal file
@@ -0,0 +1,5 @@
|
||||
<template>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
69
docs/app/assets/css/main.css
Normal file
69
docs/app/assets/css/main.css
Normal file
@@ -0,0 +1,69 @@
|
||||
@import "tailwindcss";
|
||||
@source "../../../../web/vue/src/**/demo.vue";
|
||||
@source "../../../../core/stdlib/src/**/demo.vue";
|
||||
@source "../../../../core/platform/src/**/demo.vue";
|
||||
|
||||
@theme {
|
||||
--font-sans: 'Inter', system-ui, sans-serif;
|
||||
--font-mono: 'JetBrains Mono', monospace;
|
||||
|
||||
--color-brand-50: #eef2ff;
|
||||
--color-brand-100: #e0e7ff;
|
||||
--color-brand-200: #c7d2fe;
|
||||
--color-brand-300: #a5b4fc;
|
||||
--color-brand-400: #818cf8;
|
||||
--color-brand-500: #6366f1;
|
||||
--color-brand-600: #4f46e5;
|
||||
--color-brand-700: #4338ca;
|
||||
--color-brand-800: #3730a3;
|
||||
--color-brand-900: #312e81;
|
||||
--color-brand-950: #1e1b4b;
|
||||
}
|
||||
|
||||
:root {
|
||||
--color-bg: #ffffff;
|
||||
--color-bg-soft: #f9fafb;
|
||||
--color-bg-mute: #f3f4f6;
|
||||
--color-border: #e5e7eb;
|
||||
--color-text: #111827;
|
||||
--color-text-soft: #4b5563;
|
||||
--color-text-mute: #9ca3af;
|
||||
--color-header-bg: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-bg: #0f172a;
|
||||
--color-bg-soft: #1e293b;
|
||||
--color-bg-mute: #334155;
|
||||
--color-border: #334155;
|
||||
--color-text: #f1f5f9;
|
||||
--color-text-soft: #94a3b8;
|
||||
--color-text-mute: #64748b;
|
||||
--color-header-bg: rgba(15, 23, 42, 0.8);
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--color-bg);
|
||||
color: var(--color-text);
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code, pre {
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
/* Shiki dual-theme: activate dark colors via prefers-color-scheme */
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.shiki,
|
||||
.shiki span {
|
||||
color: var(--shiki-dark) !important;
|
||||
background-color: var(--shiki-dark-bg) !important;
|
||||
font-style: var(--shiki-dark-font-style) !important;
|
||||
font-weight: var(--shiki-dark-font-weight) !important;
|
||||
text-decoration: var(--shiki-dark-text-decoration) !important;
|
||||
}
|
||||
}
|
||||
37
docs/app/components/DocsBadge.vue
Normal file
37
docs/app/components/DocsBadge.vue
Normal file
@@ -0,0 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
kind: string;
|
||||
size?: 'sm' | 'md';
|
||||
}>();
|
||||
|
||||
const kindColors: Record<string, string> = {
|
||||
function: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300',
|
||||
class: 'bg-violet-100 text-violet-700 dark:bg-violet-900/30 dark:text-violet-300',
|
||||
interface: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300',
|
||||
type: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300',
|
||||
enum: 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-300',
|
||||
variable: 'bg-slate-100 text-slate-700 dark:bg-slate-800/50 dark:text-slate-300',
|
||||
};
|
||||
|
||||
const kindLabels: Record<string, string> = {
|
||||
function: 'fn',
|
||||
class: 'C',
|
||||
interface: 'I',
|
||||
type: 'T',
|
||||
enum: 'E',
|
||||
variable: 'V',
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
:class="[
|
||||
'inline-flex items-center justify-center rounded font-mono font-medium shrink-0',
|
||||
kindColors[kind] ?? kindColors.variable,
|
||||
size === 'sm' ? 'w-5 h-5 text-[10px]' : 'w-6 h-6 text-xs',
|
||||
]"
|
||||
:title="kind"
|
||||
>
|
||||
{{ kindLabels[kind] ?? '?' }}
|
||||
</span>
|
||||
</template>
|
||||
28
docs/app/components/DocsCode.vue
Normal file
28
docs/app/components/DocsCode.vue
Normal file
@@ -0,0 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
code: string;
|
||||
lang?: string;
|
||||
}>();
|
||||
|
||||
const { highlight } = useShiki();
|
||||
const html = ref('');
|
||||
|
||||
onMounted(async () => {
|
||||
html.value = await highlight(props.code, props.lang ?? 'typescript');
|
||||
});
|
||||
|
||||
watch(() => props.code, async (newCode) => {
|
||||
html.value = await highlight(newCode, props.lang ?? 'typescript');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="code-block relative group rounded-lg border border-(--color-border) overflow-hidden max-w-full">
|
||||
<div
|
||||
v-if="html"
|
||||
class="overflow-x-auto text-sm leading-relaxed [&_pre]:p-4 [&_pre]:m-0 [&_pre]:min-w-0"
|
||||
v-html="html"
|
||||
/>
|
||||
<pre v-else class="p-4 text-sm bg-(--color-bg-soft) overflow-x-auto"><code>{{ code }}</code></pre>
|
||||
</div>
|
||||
</template>
|
||||
71
docs/app/components/DocsDemo.vue
Normal file
71
docs/app/components/DocsDemo.vue
Normal file
@@ -0,0 +1,71 @@
|
||||
<script setup lang="ts">
|
||||
import type { Component } from 'vue';
|
||||
|
||||
const props = defineProps<{
|
||||
component: Component;
|
||||
source: string;
|
||||
}>();
|
||||
|
||||
const showSource = ref(false);
|
||||
|
||||
const { highlighted, highlightReactive } = useShiki();
|
||||
|
||||
watch(showSource, async (show) => {
|
||||
if (show && !highlighted.value) {
|
||||
await highlightReactive(props.source, 'vue');
|
||||
}
|
||||
}, { immediate: false });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="border border-(--color-border) rounded-lg overflow-hidden">
|
||||
<!-- Live demo -->
|
||||
<div class="p-6 bg-(--color-bg-soft)">
|
||||
<component :is="component" />
|
||||
</div>
|
||||
|
||||
<!-- Source toggle bar -->
|
||||
<div class="flex items-center border-t border-(--color-border) bg-(--color-bg)">
|
||||
<button
|
||||
class="flex items-center gap-1.5 px-4 py-2 text-xs font-medium text-(--color-text-mute) hover:text-(--color-text) transition-colors cursor-pointer"
|
||||
@click="showSource = !showSource"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<polyline points="16 18 22 12 16 6" />
|
||||
<polyline points="8 6 2 12 8 18" />
|
||||
</svg>
|
||||
{{ showSource ? 'Hide source' : 'View source' }}
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="12"
|
||||
height="12"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
class="transition-transform"
|
||||
:class="showSource ? 'rotate-180' : ''"
|
||||
>
|
||||
<polyline points="6 9 12 15 18 9" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Source code -->
|
||||
<div v-if="showSource" class="border-t border-(--color-border)">
|
||||
<div class="overflow-x-auto text-sm" v-html="highlighted" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
46
docs/app/components/DocsMethodsList.vue
Normal file
46
docs/app/components/DocsMethodsList.vue
Normal file
@@ -0,0 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import type { MethodMeta } from '../../modules/extractor/types';
|
||||
|
||||
defineProps<{
|
||||
methods: MethodMeta[];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="methods.length > 0" class="space-y-4">
|
||||
<div
|
||||
v-for="method in methods"
|
||||
:key="method.name"
|
||||
class="border border-(--color-border) rounded-lg p-4"
|
||||
>
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<code class="text-sm font-mono font-semibold text-(--color-text)">{{ method.name }}</code>
|
||||
<span
|
||||
v-if="method.visibility !== 'public'"
|
||||
class="text-[10px] uppercase px-1.5 py-0.5 rounded bg-(--color-bg-mute) text-(--color-text-mute)"
|
||||
>
|
||||
{{ method.visibility }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p v-if="method.description" class="text-sm text-(--color-text-soft) mb-3">
|
||||
{{ method.description }}
|
||||
</p>
|
||||
|
||||
<DocsCode
|
||||
v-for="(sig, i) in method.signatures"
|
||||
:key="i"
|
||||
:code="sig"
|
||||
class="mb-3"
|
||||
/>
|
||||
|
||||
<DocsParamsTable v-if="method.params.length > 0" :params="method.params" />
|
||||
|
||||
<div v-if="method.returns" class="mt-2 text-sm">
|
||||
<span class="text-(--color-text-mute)">Returns:</span>
|
||||
<code class="ml-1 text-xs font-mono bg-(--color-bg-mute) px-1.5 py-0.5 rounded">{{ method.returns.type }}</code>
|
||||
<span v-if="method.returns.description" class="ml-2 text-(--color-text-soft)">{{ method.returns.description }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
44
docs/app/components/DocsParamsTable.vue
Normal file
44
docs/app/components/DocsParamsTable.vue
Normal file
@@ -0,0 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import type { ParamMeta } from '../../modules/extractor/types';
|
||||
|
||||
defineProps<{
|
||||
params: ParamMeta[];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="params.length > 0" class="overflow-x-auto max-w-full">
|
||||
<table class="w-full text-sm border-collapse table-fixed">
|
||||
<thead>
|
||||
<tr class="border-b border-(--color-border)">
|
||||
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Parameter</th>
|
||||
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Type</th>
|
||||
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Default</th>
|
||||
<th class="text-left py-2 font-medium text-(--color-text-soft)">Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="param in params"
|
||||
:key="param.name"
|
||||
class="border-b border-(--color-border) last:border-b-0"
|
||||
>
|
||||
<td class="py-2 pr-4">
|
||||
<code class="text-brand-600 font-mono text-xs">{{ param.name }}</code>
|
||||
<span v-if="param.optional" class="text-(--color-text-mute) text-xs ml-1">?</span>
|
||||
</td>
|
||||
<td class="py-2 pr-4 max-w-48 overflow-hidden">
|
||||
<code class="text-xs font-mono text-(--color-text-soft) bg-(--color-bg-mute) px-1.5 py-0.5 rounded break-all">{{ param.type }}</code>
|
||||
</td>
|
||||
<td class="py-2 pr-4">
|
||||
<code v-if="param.defaultValue" class="text-xs font-mono text-(--color-text-mute)">{{ param.defaultValue }}</code>
|
||||
<span v-else class="text-(--color-text-mute)">—</span>
|
||||
</td>
|
||||
<td class="py-2 text-(--color-text-soft)">
|
||||
{{ param.description || '—' }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
45
docs/app/components/DocsPropsTable.vue
Normal file
45
docs/app/components/DocsPropsTable.vue
Normal file
@@ -0,0 +1,45 @@
|
||||
<script setup lang="ts">
|
||||
import type { PropertyMeta } from '../../modules/extractor/types';
|
||||
|
||||
defineProps<{
|
||||
properties: PropertyMeta[];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="properties.length > 0" class="overflow-x-auto max-w-full">
|
||||
<table class="w-full text-sm border-collapse table-fixed">
|
||||
<thead>
|
||||
<tr class="border-b border-(--color-border)">
|
||||
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Property</th>
|
||||
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Type</th>
|
||||
<th class="text-left py-2 pr-4 font-medium text-(--color-text-soft)">Default</th>
|
||||
<th class="text-left py-2 font-medium text-(--color-text-soft)">Description</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="prop in properties"
|
||||
:key="prop.name"
|
||||
class="border-b border-(--color-border) last:border-b-0"
|
||||
>
|
||||
<td class="py-2 pr-4">
|
||||
<code class="text-brand-600 font-mono text-xs">{{ prop.name }}</code>
|
||||
<span v-if="prop.readonly" class="text-(--color-text-mute) text-[10px] ml-1 uppercase">readonly</span>
|
||||
<span v-if="prop.optional" class="text-(--color-text-mute) text-xs ml-1">?</span>
|
||||
</td>
|
||||
<td class="py-2 pr-4 max-w-48 overflow-hidden">
|
||||
<code class="text-xs font-mono text-(--color-text-soft) bg-(--color-bg-mute) px-1.5 py-0.5 rounded break-all">{{ prop.type }}</code>
|
||||
</td>
|
||||
<td class="py-2 pr-4">
|
||||
<code v-if="prop.defaultValue" class="text-xs font-mono text-(--color-text-mute)">{{ prop.defaultValue }}</code>
|
||||
<span v-else class="text-(--color-text-mute)">—</span>
|
||||
</td>
|
||||
<td class="py-2 text-(--color-text-soft)">
|
||||
{{ prop.description || '—' }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
120
docs/app/components/DocsSearch.vue
Normal file
120
docs/app/components/DocsSearch.vue
Normal file
@@ -0,0 +1,120 @@
|
||||
<script setup lang="ts">
|
||||
const { searchItems } = useDocs();
|
||||
|
||||
const isOpen = ref(false);
|
||||
const query = ref('');
|
||||
|
||||
const results = computed(() => searchItems(query.value).slice(0, 20));
|
||||
|
||||
function open() {
|
||||
isOpen.value = true;
|
||||
nextTick(() => {
|
||||
const input = document.querySelector<HTMLInputElement>('[data-search-input]');
|
||||
input?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
function close() {
|
||||
isOpen.value = false;
|
||||
query.value = '';
|
||||
}
|
||||
|
||||
// Keyboard shortcut: Cmd+K / Ctrl+K
|
||||
if (import.meta.client) {
|
||||
useEventListener(window, 'keydown', (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
||||
e.preventDefault();
|
||||
if (isOpen.value) close();
|
||||
else open();
|
||||
}
|
||||
if (e.key === 'Escape' && isOpen.value) {
|
||||
close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function useEventListener(target: Window, event: string, handler: (e: any) => void) {
|
||||
onMounted(() => target.addEventListener(event, handler));
|
||||
onUnmounted(() => target.removeEventListener(event, handler));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<button
|
||||
class="flex items-center gap-2 px-3 py-1.5 text-sm text-(--color-text-mute) bg-(--color-bg-mute) border border-(--color-border) rounded-lg hover:border-(--color-text-mute) transition-colors"
|
||||
@click="open"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
<path d="m21 21-4.3-4.3" />
|
||||
</svg>
|
||||
<span class="hidden sm:inline">Search...</span>
|
||||
<kbd class="hidden sm:inline-flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] font-mono bg-(--color-bg) border border-(--color-border) rounded">
|
||||
<span>⌘</span>K
|
||||
</kbd>
|
||||
</button>
|
||||
|
||||
<!-- Search modal -->
|
||||
<Teleport to="body">
|
||||
<Transition
|
||||
enter-active-class="duration-200 ease-out"
|
||||
enter-from-class="opacity-0"
|
||||
enter-to-class="opacity-100"
|
||||
leave-active-class="duration-150 ease-in"
|
||||
leave-from-class="opacity-100"
|
||||
leave-to-class="opacity-0"
|
||||
>
|
||||
<div v-if="isOpen" class="fixed inset-0 z-50">
|
||||
<div class="fixed inset-0 bg-black/50" @click="close" />
|
||||
|
||||
<div class="fixed inset-x-0 top-[10vh] mx-auto max-w-lg px-4">
|
||||
<div class="bg-(--color-bg) rounded-xl border border-(--color-border) shadow-2xl overflow-hidden">
|
||||
<div class="flex items-center px-4 border-b border-(--color-border)">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--color-text-mute) shrink-0">
|
||||
<circle cx="11" cy="11" r="8" />
|
||||
<path d="m21 21-4.3-4.3" />
|
||||
</svg>
|
||||
<input
|
||||
v-model="query"
|
||||
data-search-input
|
||||
type="text"
|
||||
placeholder="Search documentation..."
|
||||
class="w-full py-3 px-3 bg-transparent text-(--color-text) placeholder:text-(--color-text-mute) focus:outline-none"
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="max-h-80 overflow-y-auto">
|
||||
<div v-if="query && results.length === 0" class="py-8 text-center text-sm text-(--color-text-mute)">
|
||||
No results found
|
||||
</div>
|
||||
<ul v-else-if="results.length > 0" class="py-2">
|
||||
<li v-for="{ pkg, item } in results" :key="`${pkg.slug}-${item.slug}`">
|
||||
<NuxtLink
|
||||
:to="`/${pkg.slug}/${item.slug}`"
|
||||
class="flex items-center gap-3 px-4 py-2.5 hover:bg-(--color-bg-mute) transition-colors"
|
||||
@click="close"
|
||||
>
|
||||
<DocsBadge :kind="item.kind" size="sm" />
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-medium text-(--color-text) truncate">
|
||||
{{ item.name }}
|
||||
</div>
|
||||
<div class="text-xs text-(--color-text-mute) truncate">
|
||||
{{ pkg.name }} · {{ item.description }}
|
||||
</div>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</li>
|
||||
</ul>
|
||||
<div v-else class="py-8 text-center text-sm text-(--color-text-mute)">
|
||||
Type to search...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
24
docs/app/components/DocsTag.vue
Normal file
24
docs/app/components/DocsTag.vue
Normal file
@@ -0,0 +1,24 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
label: string;
|
||||
variant?: 'since' | 'test' | 'demo' | 'wip';
|
||||
}>();
|
||||
|
||||
const variantClasses: Record<string, string> = {
|
||||
since: 'bg-(--color-bg-mute) text-(--color-text-mute)',
|
||||
test: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
|
||||
demo: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400',
|
||||
wip: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
:class="[
|
||||
'inline-flex items-center px-2 py-0.5 text-xs font-medium rounded-full',
|
||||
variantClasses[variant ?? 'since'],
|
||||
]"
|
||||
>
|
||||
{{ label }}
|
||||
</span>
|
||||
</template>
|
||||
64
docs/app/composables/useDocs.ts
Normal file
64
docs/app/composables/useDocs.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import metadata from '#docs/metadata';
|
||||
import type { DocsMetadata, PackageMeta, CategoryMeta, ItemMeta } from '../../modules/extractor/types';
|
||||
|
||||
export function useDocs() {
|
||||
const data = metadata as unknown as DocsMetadata;
|
||||
|
||||
function getPackages(): PackageMeta[] {
|
||||
return data.packages;
|
||||
}
|
||||
|
||||
function getPackage(slug: string): PackageMeta | undefined {
|
||||
return data.packages.find(p => p.slug === slug);
|
||||
}
|
||||
|
||||
function getItem(packageSlug: string, itemSlug: string): { pkg: PackageMeta; category: CategoryMeta; item: ItemMeta } | undefined {
|
||||
const pkg = getPackage(packageSlug);
|
||||
if (!pkg) return undefined;
|
||||
|
||||
for (const category of pkg.categories) {
|
||||
const item = category.items.find(i => i.slug === itemSlug);
|
||||
if (item) return { pkg, category, item };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function searchItems(query: string): Array<{ pkg: PackageMeta; item: ItemMeta }> {
|
||||
if (!query.trim()) return [];
|
||||
const q = query.toLowerCase();
|
||||
const results: Array<{ pkg: PackageMeta; item: ItemMeta }> = [];
|
||||
|
||||
for (const pkg of data.packages) {
|
||||
for (const category of pkg.categories) {
|
||||
for (const item of category.items) {
|
||||
if (
|
||||
item.name.toLowerCase().includes(q)
|
||||
|| item.description.toLowerCase().includes(q)
|
||||
) {
|
||||
results.push({ pkg, item });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
function getTotalItems(): number {
|
||||
return data.packages.reduce(
|
||||
(sum, pkg) => sum + pkg.categories.reduce(
|
||||
(catSum, cat) => catSum + cat.items.length, 0,
|
||||
), 0,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
data,
|
||||
getPackages,
|
||||
getPackage,
|
||||
getItem,
|
||||
searchItems,
|
||||
getTotalItems,
|
||||
};
|
||||
}
|
||||
41
docs/app/composables/useShiki.ts
Normal file
41
docs/app/composables/useShiki.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { createHighlighter, type Highlighter } from 'shiki';
|
||||
|
||||
let highlighterPromise: Promise<Highlighter> | null = null;
|
||||
|
||||
function getHighlighter(): Promise<Highlighter> {
|
||||
if (!highlighterPromise) {
|
||||
highlighterPromise = createHighlighter({
|
||||
themes: ['github-light', 'github-dark'],
|
||||
langs: ['typescript', 'vue', 'json', 'bash'],
|
||||
});
|
||||
}
|
||||
return highlighterPromise;
|
||||
}
|
||||
|
||||
export function useShiki() {
|
||||
const highlighted = ref<string>('');
|
||||
const isReady = ref(false);
|
||||
|
||||
async function highlight(code: string, lang: string = 'typescript'): Promise<string> {
|
||||
const highlighter = await getHighlighter();
|
||||
return highlighter.codeToHtml(code, {
|
||||
lang,
|
||||
themes: {
|
||||
light: 'github-light',
|
||||
dark: 'github-dark',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function highlightReactive(code: string, lang: string = 'typescript'): Promise<void> {
|
||||
highlighted.value = await highlight(code, lang);
|
||||
isReady.value = true;
|
||||
}
|
||||
|
||||
return {
|
||||
highlight,
|
||||
highlighted,
|
||||
highlightReactive,
|
||||
isReady,
|
||||
};
|
||||
}
|
||||
105
docs/app/layouts/default.vue
Normal file
105
docs/app/layouts/default.vue
Normal file
@@ -0,0 +1,105 @@
|
||||
<script setup lang="ts">
|
||||
const { getPackages } = useDocs();
|
||||
const packages = getPackages();
|
||||
|
||||
const route = useRoute();
|
||||
const isSidebarOpen = ref(false);
|
||||
|
||||
const currentPackageSlug = computed(() => {
|
||||
const param = route.params.package;
|
||||
return typeof param === 'string' ? param : undefined;
|
||||
});
|
||||
|
||||
watch(() => route.path, () => {
|
||||
isSidebarOpen.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen flex flex-col">
|
||||
<!-- Header -->
|
||||
<header class="sticky top-0 z-50 border-b border-(--color-border) backdrop-blur-sm" style="background-color: var(--color-header-bg)">
|
||||
<div class="mx-auto max-w-7xl flex items-center justify-between px-4 h-14 sm:px-6">
|
||||
<div class="flex items-center gap-4">
|
||||
<button
|
||||
class="lg:hidden p-1.5 -ml-1.5 text-(--color-text-soft) hover:text-(--color-text)"
|
||||
@click="isSidebarOpen = !isSidebarOpen"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="3" y1="6" x2="21" y2="6" />
|
||||
<line x1="3" y1="12" x2="21" y2="12" />
|
||||
<line x1="3" y1="18" x2="21" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
<NuxtLink to="/" class="flex items-center gap-2 font-semibold text-(--color-text)">
|
||||
<span class="text-brand-600">@robonen</span><span class="text-(--color-text-mute)">/</span><span>tools</span>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<DocsSearch />
|
||||
<a
|
||||
href="https://github.com/robonen/tools"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="p-1.5 text-(--color-text-soft) hover:text-(--color-text) transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="mx-auto max-w-7xl w-full flex flex-1 px-4 sm:px-6">
|
||||
<!-- Sidebar -->
|
||||
<aside
|
||||
:class="[
|
||||
'fixed inset-y-0 left-0 z-40 w-64 bg-(--color-bg) border-r border-(--color-border) pt-14 transform transition-transform lg:sticky lg:top-14 lg:z-auto lg:h-[calc(100vh-3.5rem)] lg:w-56 lg:shrink-0 lg:translate-x-0 lg:pt-0 lg:border-r-0 lg:bg-transparent lg:transform-none',
|
||||
isSidebarOpen ? 'translate-x-0' : '-translate-x-full',
|
||||
]"
|
||||
>
|
||||
<nav class="h-full overflow-y-auto py-6 px-4 lg:pr-6 lg:pl-0 overscroll-contain">
|
||||
<div v-for="pkg in packages" :key="pkg.slug" class="mb-6">
|
||||
<NuxtLink
|
||||
:to="`/${pkg.slug}`"
|
||||
class="block text-xs font-semibold uppercase tracking-wider mb-2"
|
||||
:class="currentPackageSlug === pkg.slug ? 'text-brand-600' : 'text-(--color-text-mute) hover:text-(--color-text-soft)'"
|
||||
>
|
||||
{{ pkg.name }}
|
||||
</NuxtLink>
|
||||
<div v-for="category in pkg.categories" :key="category.slug" class="mb-3">
|
||||
<div class="text-xs font-medium text-(--color-text-mute) mb-1 pl-2">
|
||||
{{ category.name }}
|
||||
</div>
|
||||
<ul class="space-y-0.5">
|
||||
<li v-for="item in category.items" :key="item.slug">
|
||||
<NuxtLink
|
||||
:to="`/${pkg.slug}/${item.slug}`"
|
||||
class="block py-1 px-2 text-sm rounded-md transition-colors"
|
||||
active-class="bg-brand-50 text-brand-700 dark:bg-brand-950 dark:text-brand-300 font-medium"
|
||||
:class="route.path !== `/${pkg.slug}/${item.slug}` ? 'text-(--color-text-soft) hover:text-(--color-text) hover:bg-(--color-bg-mute)' : ''"
|
||||
>
|
||||
{{ item.name }}
|
||||
</NuxtLink>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<!-- Sidebar overlay -->
|
||||
<div
|
||||
v-if="isSidebarOpen"
|
||||
class="fixed inset-0 z-30 bg-black/20 lg:hidden"
|
||||
@click="isSidebarOpen = false"
|
||||
/>
|
||||
|
||||
<!-- Main content -->
|
||||
<main class="flex-1 min-w-0 overflow-hidden py-8 lg:pl-8">
|
||||
<slot />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
204
docs/app/pages/[package]/[utility].vue
Normal file
204
docs/app/pages/[package]/[utility].vue
Normal file
@@ -0,0 +1,204 @@
|
||||
<script setup lang="ts">
|
||||
import { demos } from '#docs/demos';
|
||||
|
||||
const route = useRoute();
|
||||
const { getItem } = useDocs();
|
||||
|
||||
const packageSlug = computed(() => route.params.package as string);
|
||||
const utilitySlug = computed(() => route.params.utility as string);
|
||||
|
||||
const result = computed(() => getItem(packageSlug.value, utilitySlug.value));
|
||||
|
||||
if (!result.value) {
|
||||
throw createError({
|
||||
statusCode: 404,
|
||||
message: `Item "${utilitySlug.value}" not found in package "${packageSlug.value}"`,
|
||||
});
|
||||
}
|
||||
|
||||
const { pkg, category, item } = result.value;
|
||||
|
||||
useHead({
|
||||
title: `${item.name} — ${pkg.name} — @robonen/tools`,
|
||||
meta: [
|
||||
{ name: 'description', content: item.description },
|
||||
],
|
||||
});
|
||||
|
||||
const sourceUrl = computed(() => `https://github.com/robonen/tools/blob/main/${item.sourcePath}`);
|
||||
|
||||
const demoComponent = computed(() => {
|
||||
const key = `${pkg.slug}/${item.slug}`;
|
||||
return demos[key] ?? null;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="item" class="max-w-3xl min-w-0">
|
||||
<!-- Breadcrumb -->
|
||||
<nav class="flex items-center gap-1.5 text-sm text-(--color-text-mute) mb-6">
|
||||
<NuxtLink :to="`/${pkg.slug}`" class="hover:text-(--color-text-soft) transition-colors">
|
||||
{{ pkg.name }}
|
||||
</NuxtLink>
|
||||
<span>/</span>
|
||||
<span>{{ category.name }}</span>
|
||||
<span>/</span>
|
||||
<span class="text-(--color-text)">{{ item.name }}</span>
|
||||
</nav>
|
||||
|
||||
<!-- Header -->
|
||||
<div class="mb-8">
|
||||
<div class="flex items-center gap-3 mb-2 flex-wrap">
|
||||
<DocsBadge :kind="item.kind" size="md" />
|
||||
<h1 class="text-2xl font-bold font-mono tracking-tight text-(--color-text)">
|
||||
{{ item.name }}
|
||||
</h1>
|
||||
<DocsTag v-if="item.since" :label="`v${item.since}`" variant="since" />
|
||||
<DocsTag v-if="item.hasTests" label="tested" variant="test" />
|
||||
<DocsTag v-if="item.hasDemo" label="demo" variant="demo" />
|
||||
</div>
|
||||
<p class="text-(--color-text-soft) leading-relaxed">
|
||||
{{ item.description }}
|
||||
</p>
|
||||
|
||||
<!-- Links (source, tests) -->
|
||||
<div class="flex items-center gap-4 mt-3 text-sm">
|
||||
<a
|
||||
:href="sourceUrl"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center gap-1.5 text-(--color-text-mute) hover:text-(--color-text) transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4" />
|
||||
<path d="M9 18c-4.51 2-5-2-7-2" />
|
||||
</svg>
|
||||
Source
|
||||
</a>
|
||||
<a
|
||||
v-if="item.hasTests"
|
||||
:href="`${sourceUrl.replace('index.ts', 'index.test.ts')}`"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="flex items-center gap-1.5 text-(--color-text-mute) hover:text-(--color-text) transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
<path d="m9 15 2 2 4-4" />
|
||||
</svg>
|
||||
Tests
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Examples (moved to top for quick reference) -->
|
||||
<section v-if="item.examples.length > 0" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
{{ item.examples.length > 1 ? 'Examples' : 'Example' }}
|
||||
</h2>
|
||||
<div class="space-y-3">
|
||||
<DocsCode v-for="(example, i) in item.examples" :key="i" :code="example" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Demo -->
|
||||
<section v-if="item.hasDemo && demoComponent" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Demo
|
||||
</h2>
|
||||
<DocsDemo :component="demoComponent" :source="item.demoSource" />
|
||||
</section>
|
||||
|
||||
<!-- Signatures -->
|
||||
<section v-if="item.signatures.length > 0" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
{{ item.signatures.length > 1 ? 'Signatures' : 'Signature' }}
|
||||
</h2>
|
||||
<div class="space-y-2">
|
||||
<DocsCode v-for="(sig, i) in item.signatures" :key="i" :code="sig" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Type Parameters -->
|
||||
<section v-if="item.typeParams.length > 0" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Type Parameters
|
||||
</h2>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="tp in item.typeParams"
|
||||
:key="tp.name"
|
||||
class="flex items-baseline gap-2 text-sm"
|
||||
>
|
||||
<code class="font-mono font-medium text-brand-600">{{ tp.name }}</code>
|
||||
<span v-if="tp.constraint" class="text-(--color-text-mute)">
|
||||
extends <code class="font-mono text-xs">{{ tp.constraint }}</code>
|
||||
</span>
|
||||
<span v-if="tp.default" class="text-(--color-text-mute)">
|
||||
= <code class="font-mono text-xs">{{ tp.default }}</code>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Parameters -->
|
||||
<section v-if="item.params.length > 0" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Parameters
|
||||
</h2>
|
||||
<DocsParamsTable :params="item.params" />
|
||||
</section>
|
||||
|
||||
<!-- Return value -->
|
||||
<section v-if="item.returns" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Returns
|
||||
</h2>
|
||||
<div class="flex items-baseline gap-2 text-sm">
|
||||
<code class="font-mono bg-(--color-bg-mute) px-2 py-1 rounded text-xs break-all">{{ item.returns.type }}</code>
|
||||
<span v-if="item.returns.description" class="text-(--color-text-soft)">{{ item.returns.description }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Properties (interfaces, classes) -->
|
||||
<section v-if="item.properties.length > 0" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Properties
|
||||
</h2>
|
||||
<DocsPropsTable :properties="item.properties" />
|
||||
</section>
|
||||
|
||||
<!-- Methods (classes) -->
|
||||
<section v-if="item.methods.length > 0" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Methods
|
||||
</h2>
|
||||
<DocsMethodsList :methods="item.methods" />
|
||||
</section>
|
||||
|
||||
<!-- Related Types -->
|
||||
<section v-if="item.relatedTypes?.length" class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-3">
|
||||
Related Types
|
||||
</h2>
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-for="rt in item.relatedTypes"
|
||||
:key="rt.name"
|
||||
class="border border-(--color-border) rounded-lg p-4 bg-(--color-bg-soft)"
|
||||
>
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<DocsBadge :kind="rt.kind" size="sm" />
|
||||
<h3 class="font-mono font-semibold text-sm">{{ rt.name }}</h3>
|
||||
</div>
|
||||
<p v-if="rt.description" class="text-sm text-(--color-text-soft) mb-3">
|
||||
{{ rt.description }}
|
||||
</p>
|
||||
<DocsCode v-if="rt.signatures.length > 0" :code="rt.signatures[0]!" />
|
||||
<DocsPropsTable v-if="rt.properties.length > 0" :properties="rt.properties" class="mt-3" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
74
docs/app/pages/[package]/index.vue
Normal file
74
docs/app/pages/[package]/index.vue
Normal file
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
const route = useRoute();
|
||||
const { getPackage } = useDocs();
|
||||
|
||||
const slug = computed(() => route.params.package as string);
|
||||
const pkg = computed(() => getPackage(slug.value));
|
||||
|
||||
if (!pkg.value) {
|
||||
throw createError({ statusCode: 404, message: `Package "${slug.value}" not found` });
|
||||
}
|
||||
|
||||
useHead({
|
||||
title: `${pkg.value.name} — @robonen/tools`,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="pkg" class="max-w-3xl min-w-0">
|
||||
<!-- Header -->
|
||||
<div class="mb-8">
|
||||
<div class="flex items-center gap-3 mb-2">
|
||||
<h1 class="text-2xl font-bold tracking-tight text-(--color-text)">
|
||||
{{ pkg.name }}
|
||||
</h1>
|
||||
<DocsTag :label="`v${pkg.version}`" variant="since" />
|
||||
</div>
|
||||
<p class="text-(--color-text-soft)">
|
||||
{{ pkg.description }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Install -->
|
||||
<div class="mb-8">
|
||||
<h2 class="text-sm font-semibold uppercase tracking-wider text-(--color-text-mute) mb-2">
|
||||
Installation
|
||||
</h2>
|
||||
<DocsCode :code="`pnpm add ${pkg.name}`" lang="bash" />
|
||||
</div>
|
||||
|
||||
<!-- Categories -->
|
||||
<div v-for="category in pkg.categories" :key="category.slug" class="mb-8">
|
||||
<h2 class="text-lg font-semibold text-(--color-text) mb-4 pb-2 border-b border-(--color-border)">
|
||||
{{ category.name }}
|
||||
</h2>
|
||||
|
||||
<div class="grid gap-2">
|
||||
<NuxtLink
|
||||
v-for="item in category.items"
|
||||
:key="item.slug"
|
||||
:to="`/${pkg.slug}/${item.slug}`"
|
||||
class="group flex items-center gap-3 p-3 rounded-lg border border-(--color-border) hover:border-brand-300 hover:bg-(--color-bg-soft) transition-all"
|
||||
>
|
||||
<DocsBadge :kind="item.kind" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-mono text-sm font-medium text-(--color-text) group-hover:text-brand-600 transition-colors">
|
||||
{{ item.name }}
|
||||
</span>
|
||||
<DocsTag v-if="item.since" :label="`v${item.since}`" variant="since" />
|
||||
<DocsTag v-if="item.hasTests" label="tested" variant="test" />
|
||||
<DocsTag v-if="item.hasDemo" label="demo" variant="demo" />
|
||||
</div>
|
||||
<p v-if="item.description" class="text-sm text-(--color-text-mute) mt-0.5 truncate">
|
||||
{{ item.description }}
|
||||
</p>
|
||||
</div>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-(--color-text-mute) group-hover:text-brand-600 transition-colors shrink-0">
|
||||
<polyline points="9 18 15 12 9 6" />
|
||||
</svg>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
73
docs/app/pages/index.vue
Normal file
73
docs/app/pages/index.vue
Normal file
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
const { getPackages, getTotalItems } = useDocs();
|
||||
const packages = getPackages();
|
||||
const totalItems = getTotalItems();
|
||||
|
||||
const packageIcons: Record<string, string> = {
|
||||
stdlib: '📦',
|
||||
platform: '🖥️',
|
||||
vue: '💚',
|
||||
oxlint: '🔍',
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="max-w-3xl min-w-0">
|
||||
<!-- Hero -->
|
||||
<div class="mb-12">
|
||||
<h1 class="text-3xl font-bold tracking-tight text-(--color-text) mb-3">
|
||||
@robonen/tools
|
||||
</h1>
|
||||
<p class="text-lg text-(--color-text-soft) leading-relaxed">
|
||||
A collection of TypeScript utilities, Vue composables, and developer tools.
|
||||
Auto-generated documentation from source types and JSDoc annotations.
|
||||
</p>
|
||||
<div class="mt-4 flex items-center gap-4 text-sm text-(--color-text-mute)">
|
||||
<span>{{ packages.length }} packages</span>
|
||||
<span>·</span>
|
||||
<span>{{ totalItems }} documented items</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Package cards -->
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<NuxtLink
|
||||
v-for="pkg in packages"
|
||||
:key="pkg.slug"
|
||||
:to="`/${pkg.slug}`"
|
||||
class="group block p-5 rounded-xl border border-(--color-border) hover:border-brand-300 hover:shadow-sm transition-all bg-(--color-bg)"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<span class="text-2xl">{{ packageIcons[pkg.slug] ?? '📦' }}</span>
|
||||
<div class="min-w-0">
|
||||
<h2 class="font-semibold text-(--color-text) group-hover:text-brand-600 transition-colors">
|
||||
{{ pkg.name }}
|
||||
</h2>
|
||||
<p class="text-sm text-(--color-text-soft) mt-1">
|
||||
{{ pkg.description }}
|
||||
</p>
|
||||
<div class="mt-3 flex items-center gap-3 text-xs text-(--color-text-mute)">
|
||||
<span>v{{ pkg.version }}</span>
|
||||
<span>·</span>
|
||||
<span>{{ pkg.categories.reduce((sum, c) => sum + c.items.length, 0) }} items</span>
|
||||
<span>·</span>
|
||||
<span>{{ pkg.categories.length }} categories</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
||||
<!-- Quick start -->
|
||||
<div class="mt-12">
|
||||
<h2 class="text-lg font-semibold text-(--color-text) mb-4">
|
||||
Quick Start
|
||||
</h2>
|
||||
<div class="space-y-3">
|
||||
<div v-for="pkg in packages" :key="pkg.slug">
|
||||
<DocsCode :code="`pnpm add ${pkg.name}`" lang="bash" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
744
docs/modules/extractor/extract.ts
Normal file
744
docs/modules/extractor/extract.ts
Normal file
@@ -0,0 +1,744 @@
|
||||
/**
|
||||
* ts-morph based metadata extractor for @robonen/tools packages.
|
||||
*
|
||||
* Scans package source files, extracts JSDoc annotations and TypeScript signatures,
|
||||
* and produces a structured JSON metadata file consumed by the Nuxt docs site.
|
||||
*/
|
||||
|
||||
import { resolve, relative, dirname } from 'node:path';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import {
|
||||
Project,
|
||||
type SourceFile,
|
||||
type FunctionDeclaration,
|
||||
type ClassDeclaration,
|
||||
type InterfaceDeclaration,
|
||||
type TypeAliasDeclaration,
|
||||
type JSDoc,
|
||||
type JSDocTag,
|
||||
type MethodDeclaration,
|
||||
type PropertyDeclaration,
|
||||
type PropertySignature,
|
||||
SyntaxKind,
|
||||
type Node,
|
||||
} from 'ts-morph';
|
||||
import type {
|
||||
DocsMetadata,
|
||||
PackageMeta,
|
||||
CategoryMeta,
|
||||
ItemMeta,
|
||||
ParamMeta,
|
||||
ReturnMeta,
|
||||
TypeParamMeta,
|
||||
MethodMeta,
|
||||
PropertyMeta,
|
||||
} from './types';
|
||||
|
||||
/** Repository root — docs/modules/extractor → three levels up */
|
||||
const ROOT = resolve(import.meta.dirname, '..', '..', '..');
|
||||
|
||||
/** Packages to document — relative paths from repo root */
|
||||
const PACKAGES: PackageConfig[] = [
|
||||
{ path: 'core/stdlib', slug: 'stdlib' },
|
||||
{ path: 'core/platform', slug: 'platform' },
|
||||
{ path: 'web/vue', slug: 'vue' },
|
||||
{ path: 'configs/oxlint', slug: 'oxlint' },
|
||||
];
|
||||
|
||||
interface PackageConfig {
|
||||
path: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
function toKebabCase(str: string): string {
|
||||
return str
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
||||
.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function slugify(name: string): string {
|
||||
return toKebabCase(name);
|
||||
}
|
||||
|
||||
function getJsDocTags(jsdocs: JSDoc[]): JSDocTag[] {
|
||||
return jsdocs.flatMap(doc => doc.getTags());
|
||||
}
|
||||
|
||||
function getTagValue(tags: JSDocTag[], tagName: string): string {
|
||||
const tag = tags.find(t => t.getTagName() === tagName);
|
||||
if (!tag) return '';
|
||||
const comment = tag.getCommentText();
|
||||
return comment?.trim() ?? '';
|
||||
}
|
||||
|
||||
function getTagValues(tags: JSDocTag[], tagName: string): string[] {
|
||||
return tags
|
||||
.filter(t => t.getTagName() === tagName)
|
||||
.map(t => {
|
||||
const comment = t.getCommentText();
|
||||
return comment?.trim() ?? '';
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function getDescription(jsdocs: JSDoc[], tags: JSDocTag[]): string {
|
||||
// Try @description tag first
|
||||
const descTag = getTagValue(tags, 'description');
|
||||
if (descTag) return descTag;
|
||||
|
||||
// Fall back to the main JSDoc comment text
|
||||
for (const doc of jsdocs) {
|
||||
const desc = doc.getDescription().trim();
|
||||
if (desc) return desc;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function getExamples(tags: JSDocTag[]): string[] {
|
||||
return tags
|
||||
.filter(t => t.getTagName() === 'example')
|
||||
.map(t => {
|
||||
const text = t.getCommentText()?.trim() ?? '';
|
||||
// Strip surrounding ```ts ... ``` if present
|
||||
return text.replace(/^```(?:ts|typescript)?\n?/, '').replace(/\n?```$/, '').trim();
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function extractParams(tags: JSDocTag[], node: FunctionDeclaration | MethodDeclaration): ParamMeta[] {
|
||||
const params: ParamMeta[] = [];
|
||||
const paramTags = tags.filter(t => t.getTagName() === 'param');
|
||||
|
||||
for (const param of node.getParameters()) {
|
||||
const name = param.getName();
|
||||
const type = param.getType().getText(param);
|
||||
const optional = param.isOptional();
|
||||
const defaultValue = param.getInitializer()?.getText() ?? null;
|
||||
|
||||
// Find matching @param tag
|
||||
const paramTag = paramTags.find(t => {
|
||||
const text = t.getCommentText() ?? '';
|
||||
const tagText = t.getText();
|
||||
return tagText.includes(name);
|
||||
});
|
||||
|
||||
let description = '';
|
||||
if (paramTag) {
|
||||
const comment = paramTag.getCommentText() ?? '';
|
||||
// Remove leading {type} annotation and param name
|
||||
description = comment
|
||||
.replace(/^\{[^}]*\}\s*/, '')
|
||||
.replace(new RegExp(`^${name}\\s*[-–—]?\\s*`), '')
|
||||
.replace(new RegExp(`^${name}\\s+`), '')
|
||||
.replace(/^[-–—]\s*/, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
params.push({ name, type, description, optional, defaultValue });
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
function extractTypeParams(node: FunctionDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration): TypeParamMeta[] {
|
||||
const typeParams = node.getTypeParameters();
|
||||
return typeParams.map(tp => ({
|
||||
name: tp.getName(),
|
||||
constraint: tp.getConstraint()?.getText() ?? null,
|
||||
default: tp.getDefault()?.getText() ?? null,
|
||||
description: '',
|
||||
}));
|
||||
}
|
||||
|
||||
function extractReturnMeta(tags: JSDocTag[], node: FunctionDeclaration | MethodDeclaration): ReturnMeta | null {
|
||||
const returnType = node.getReturnType().getText(node);
|
||||
if (returnType === 'void') return null;
|
||||
|
||||
const returnsTag = getTagValue(tags, 'returns') || getTagValue(tags, 'return');
|
||||
const description = returnsTag.replace(/^\{[^}]*\}\s*/, '').trim();
|
||||
|
||||
return { type: returnType, description };
|
||||
}
|
||||
|
||||
function extractMethodMeta(method: MethodDeclaration): MethodMeta {
|
||||
const jsdocs = method.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
const name = method.getName();
|
||||
|
||||
// Simplified signature
|
||||
const signature = method.getText().split('{')[0]?.trim() ?? '';
|
||||
|
||||
const visibility = method.getScope() ?? 'public';
|
||||
|
||||
return {
|
||||
name,
|
||||
description: getDescription(jsdocs, tags),
|
||||
signatures: [signature],
|
||||
params: extractParams(tags, method),
|
||||
returns: extractReturnMeta(tags, method),
|
||||
visibility,
|
||||
};
|
||||
}
|
||||
|
||||
function extractPropertyMeta(prop: PropertyDeclaration | PropertySignature): PropertyMeta {
|
||||
const jsdocs = prop.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
|
||||
return {
|
||||
name: prop.getName(),
|
||||
type: prop.getType().getText(prop),
|
||||
description: getDescription(jsdocs, tags),
|
||||
optional: prop.hasQuestionToken?.() ?? false,
|
||||
defaultValue: getTagValue(tags, 'default') || null,
|
||||
readonly: prop.isReadonly?.() ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
function getSourceDir(itemPath: string): string {
|
||||
// Get the directory containing the item's index.ts
|
||||
return dirname(itemPath);
|
||||
}
|
||||
|
||||
function hasDemoFile(sourceFilePath: string): boolean {
|
||||
const dir = getSourceDir(sourceFilePath);
|
||||
return existsSync(resolve(dir, 'demo.vue'));
|
||||
}
|
||||
|
||||
function readDemoSource(sourceFilePath: string): string {
|
||||
const dir = getSourceDir(sourceFilePath);
|
||||
const demoPath = resolve(dir, 'demo.vue');
|
||||
if (!existsSync(demoPath)) return '';
|
||||
return readFileSync(demoPath, 'utf-8');
|
||||
}
|
||||
|
||||
function hasTestFile(sourceFilePath: string): boolean {
|
||||
const dir = getSourceDir(sourceFilePath);
|
||||
return existsSync(resolve(dir, 'index.test.ts'));
|
||||
}
|
||||
|
||||
function inferCategory(sourceFilePath: string, tags: JSDocTag[]): string {
|
||||
// Try @category tag first
|
||||
const categoryTag = getTagValue(tags, 'category');
|
||||
if (categoryTag) return categoryTag;
|
||||
|
||||
// Infer from directory structure
|
||||
const parts = sourceFilePath.split('/src/');
|
||||
if (parts[1]) {
|
||||
const segments = parts[1].split('/');
|
||||
// For patterns like: composables/browser/useIntervalFn/index.ts → "Browser"
|
||||
// For patterns like: arrays/cluster/index.ts → "Arrays"
|
||||
if (segments.length >= 2) {
|
||||
const category = segments.length >= 3 ? segments[1] : segments[0];
|
||||
if (category) {
|
||||
return category.charAt(0).toUpperCase() + category.slice(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 'General';
|
||||
}
|
||||
|
||||
// ── Extraction ─────────────────────────────────────────────────────────────
|
||||
|
||||
function extractFunction(fn: FunctionDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
|
||||
const name = fn.getName();
|
||||
if (!name) return null;
|
||||
|
||||
// Skip private/internal functions
|
||||
if (name.startsWith('_')) return null;
|
||||
|
||||
const jsdocs = fn.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
const description = getDescription(jsdocs, tags);
|
||||
const category = inferCategory(sourceFilePath, tags);
|
||||
|
||||
// Get signature text without body
|
||||
const signatureText = fn.getOverloads().length > 0
|
||||
? fn.getOverloads().map(o => o.getText().trim())
|
||||
: [fn.getText().split('{')[0]?.trim() + '{ ... }'];
|
||||
|
||||
return {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
kind: 'function',
|
||||
description,
|
||||
since: getTagValue(tags, 'since'),
|
||||
signatures: signatureText,
|
||||
params: extractParams(tags, fn),
|
||||
returns: extractReturnMeta(tags, fn),
|
||||
typeParams: extractTypeParams(fn),
|
||||
examples: getExamples(tags),
|
||||
methods: [],
|
||||
properties: [],
|
||||
hasDemo: hasDemoFile(sourceFilePath),
|
||||
demoSource: readDemoSource(sourceFilePath),
|
||||
hasTests: hasTestFile(sourceFilePath),
|
||||
relatedTypes: [],
|
||||
sourcePath: relative(ROOT, sourceFilePath),
|
||||
entryPoint,
|
||||
};
|
||||
}
|
||||
|
||||
function extractClass(cls: ClassDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
|
||||
const name = cls.getName();
|
||||
if (!name) return null;
|
||||
|
||||
const jsdocs = cls.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
|
||||
const methods = cls.getMethods()
|
||||
.filter(m => (m.getScope() ?? 'public') === 'public')
|
||||
.filter(m => !m.getName().startsWith('_'))
|
||||
.map(extractMethodMeta);
|
||||
|
||||
const properties = cls.getProperties()
|
||||
.filter(p => (p.getScope() ?? 'public') === 'public')
|
||||
.map(p => extractPropertyMeta(p));
|
||||
|
||||
// Also include get accessors as readonly properties
|
||||
const getters = cls.getGetAccessors()
|
||||
.filter(g => (g.getScope() ?? 'public') === 'public')
|
||||
.map(g => ({
|
||||
name: g.getName(),
|
||||
type: g.getReturnType().getText(g),
|
||||
description: getDescription(g.getJsDocs(), getJsDocTags(g.getJsDocs())),
|
||||
optional: false,
|
||||
defaultValue: null,
|
||||
readonly: true,
|
||||
}));
|
||||
|
||||
// Build class signature
|
||||
const typeParams = cls.getTypeParameters();
|
||||
const typeParamStr = typeParams.length > 0
|
||||
? `<${typeParams.map(tp => tp.getText()).join(', ')}>`
|
||||
: '';
|
||||
const extendsClause = cls.getExtends() ? ` extends ${cls.getExtends()!.getText()}` : '';
|
||||
const implementsClause = cls.getImplements().length > 0
|
||||
? ` implements ${cls.getImplements().map(i => i.getText()).join(', ')}`
|
||||
: '';
|
||||
const signature = `class ${name}${typeParamStr}${extendsClause}${implementsClause}`;
|
||||
|
||||
return {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
kind: 'class',
|
||||
description: getDescription(jsdocs, tags),
|
||||
since: getTagValue(tags, 'since'),
|
||||
signatures: [signature],
|
||||
params: [],
|
||||
returns: null,
|
||||
typeParams: extractTypeParams(cls),
|
||||
examples: getExamples(tags),
|
||||
methods,
|
||||
properties: [...properties, ...getters],
|
||||
hasDemo: hasDemoFile(sourceFilePath),
|
||||
demoSource: readDemoSource(sourceFilePath),
|
||||
hasTests: hasTestFile(sourceFilePath),
|
||||
relatedTypes: [],
|
||||
sourcePath: relative(ROOT, sourceFilePath),
|
||||
entryPoint,
|
||||
};
|
||||
}
|
||||
|
||||
function extractInterface(iface: InterfaceDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
|
||||
const name = iface.getName();
|
||||
if (!name) return null;
|
||||
|
||||
const jsdocs = iface.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
|
||||
const properties = iface.getProperties().map(p => extractPropertyMeta(p));
|
||||
|
||||
const typeParams = iface.getTypeParameters();
|
||||
const typeParamStr = typeParams.length > 0
|
||||
? `<${typeParams.map(tp => tp.getText()).join(', ')}>`
|
||||
: '';
|
||||
const extendsExprs = iface.getExtends();
|
||||
const extendsStr = extendsExprs.length > 0
|
||||
? ` extends ${extendsExprs.map(e => e.getText()).join(', ')}`
|
||||
: '';
|
||||
const signature = `interface ${name}${typeParamStr}${extendsStr}`;
|
||||
|
||||
return {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
kind: 'interface',
|
||||
description: getDescription(jsdocs, tags),
|
||||
since: getTagValue(tags, 'since'),
|
||||
signatures: [signature],
|
||||
params: [],
|
||||
returns: null,
|
||||
typeParams: extractTypeParams(iface),
|
||||
examples: getExamples(tags),
|
||||
methods: [],
|
||||
properties,
|
||||
hasDemo: hasDemoFile(sourceFilePath),
|
||||
demoSource: readDemoSource(sourceFilePath),
|
||||
hasTests: hasTestFile(sourceFilePath),
|
||||
relatedTypes: [],
|
||||
sourcePath: relative(ROOT, sourceFilePath),
|
||||
entryPoint,
|
||||
};
|
||||
}
|
||||
|
||||
function extractTypeAlias(typeAlias: TypeAliasDeclaration, sourceFilePath: string, entryPoint: string): ItemMeta | null {
|
||||
const name = typeAlias.getName();
|
||||
if (!name) return null;
|
||||
|
||||
const jsdocs = typeAlias.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
|
||||
const signature = typeAlias.getText().trim();
|
||||
|
||||
return {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
kind: 'type',
|
||||
description: getDescription(jsdocs, tags),
|
||||
since: getTagValue(tags, 'since'),
|
||||
signatures: [signature],
|
||||
params: [],
|
||||
returns: null,
|
||||
typeParams: extractTypeParams(typeAlias),
|
||||
examples: getExamples(tags),
|
||||
methods: [],
|
||||
properties: [],
|
||||
hasDemo: hasDemoFile(sourceFilePath),
|
||||
demoSource: readDemoSource(sourceFilePath),
|
||||
hasTests: hasTestFile(sourceFilePath),
|
||||
relatedTypes: [],
|
||||
sourcePath: relative(ROOT, sourceFilePath),
|
||||
entryPoint,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Source Tree Walking ────────────────────────────────────────────────────
|
||||
|
||||
function collectExportedItems(
|
||||
sourceFile: SourceFile,
|
||||
entryPoint: string,
|
||||
visited: Set<string> = new Set(),
|
||||
): ItemMeta[] {
|
||||
const filePath = sourceFile.getFilePath();
|
||||
if (visited.has(filePath)) return [];
|
||||
visited.add(filePath);
|
||||
|
||||
const items: ItemMeta[] = [];
|
||||
|
||||
// Direct exports from this file
|
||||
for (const fn of sourceFile.getFunctions()) {
|
||||
if (!fn.isExported()) continue;
|
||||
|
||||
// Skip implementation signatures that have overloads
|
||||
const overloads = fn.getOverloads();
|
||||
if (overloads.length > 0) {
|
||||
// Use the first overload's doc for metadata, but collect all signatures
|
||||
const firstOverload = overloads[0]!;
|
||||
const jsdocs = firstOverload.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
const name = fn.getName();
|
||||
if (!name || name.startsWith('_')) continue;
|
||||
|
||||
const item: ItemMeta = {
|
||||
name,
|
||||
slug: slugify(name),
|
||||
kind: 'function',
|
||||
description: getDescription(jsdocs, tags),
|
||||
since: getTagValue(tags, 'since'),
|
||||
signatures: overloads.map(o => o.getText().trim()),
|
||||
params: extractParams(tags, fn),
|
||||
returns: extractReturnMeta(tags, fn),
|
||||
typeParams: extractTypeParams(fn),
|
||||
examples: getExamples(tags),
|
||||
methods: [],
|
||||
properties: [],
|
||||
hasDemo: hasDemoFile(filePath),
|
||||
demoSource: readDemoSource(filePath),
|
||||
hasTests: hasTestFile(filePath),
|
||||
relatedTypes: [],
|
||||
sourcePath: relative(ROOT, filePath),
|
||||
entryPoint,
|
||||
};
|
||||
items.push(item);
|
||||
} else {
|
||||
const item = extractFunction(fn, filePath, entryPoint);
|
||||
if (item) items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
for (const cls of sourceFile.getClasses()) {
|
||||
if (!cls.isExported()) continue;
|
||||
const item = extractClass(cls, filePath, entryPoint);
|
||||
if (item) items.push(item);
|
||||
}
|
||||
|
||||
for (const iface of sourceFile.getInterfaces()) {
|
||||
if (!iface.isExported()) continue;
|
||||
// Skip internal interfaces (e.g. Options, Return types that are documented inline)
|
||||
const name = iface.getName();
|
||||
const jsdocs = iface.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
const hasCategory = getTagValue(tags, 'category') !== '';
|
||||
// Only include interfaces with @category or that have significant documentation
|
||||
if (!hasCategory && jsdocs.length === 0) continue;
|
||||
const item = extractInterface(iface, filePath, entryPoint);
|
||||
if (item) items.push(item);
|
||||
}
|
||||
|
||||
for (const typeAlias of sourceFile.getTypeAliases()) {
|
||||
if (!typeAlias.isExported()) continue;
|
||||
const jsdocs = typeAlias.getJsDocs();
|
||||
const tags = getJsDocTags(jsdocs);
|
||||
const hasCategory = getTagValue(tags, 'category') !== '';
|
||||
if (!hasCategory && jsdocs.length === 0) continue;
|
||||
const item = extractTypeAlias(typeAlias, filePath, entryPoint);
|
||||
if (item) items.push(item);
|
||||
}
|
||||
|
||||
// Follow barrel re-exports: export * from './...'
|
||||
for (const exportDecl of sourceFile.getExportDeclarations()) {
|
||||
const moduleSpecifier = exportDecl.getModuleSpecifierValue();
|
||||
if (!moduleSpecifier) continue;
|
||||
|
||||
const referencedFile = exportDecl.getModuleSpecifierSourceFile();
|
||||
if (referencedFile) {
|
||||
items.push(...collectExportedItems(referencedFile, entryPoint, visited));
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
// ── Co-located Type Grouping ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Groups types/interfaces from `types.ts` files with their sibling
|
||||
* class/function items from the same directory.
|
||||
*
|
||||
* For example, Transition and TransitionConfig from StateMachine/types.ts
|
||||
* get attached as relatedTypes of StateMachine and AsyncStateMachine.
|
||||
*/
|
||||
function groupCoLocatedTypes(items: ItemMeta[]): ItemMeta[] {
|
||||
// Build a map: directory → items from types.ts
|
||||
const typesByDir = new Map<string, ItemMeta[]>();
|
||||
// Build a map: directory → primary items (classes, functions)
|
||||
const primaryByDir = new Map<string, ItemMeta[]>();
|
||||
|
||||
for (const item of items) {
|
||||
const dir = dirname(item.sourcePath);
|
||||
const isTypesFile = item.sourcePath.endsWith('/types.ts');
|
||||
const isSecondary = isTypesFile && (item.kind === 'type' || item.kind === 'interface');
|
||||
|
||||
if (isSecondary) {
|
||||
const existing = typesByDir.get(dir) ?? [];
|
||||
existing.push(item);
|
||||
typesByDir.set(dir, existing);
|
||||
} else {
|
||||
const existing = primaryByDir.get(dir) ?? [];
|
||||
existing.push(item);
|
||||
primaryByDir.set(dir, existing);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach co-located types to their primary items
|
||||
const absorbed = new Set<string>();
|
||||
for (const entry of Array.from(typesByDir.entries())) {
|
||||
const [dir, types] = entry;
|
||||
const primaries = primaryByDir.get(dir);
|
||||
if (!primaries || primaries.length === 0) continue;
|
||||
|
||||
// Distribute types to all primary items in the same directory
|
||||
for (const primary of primaries) {
|
||||
primary.relatedTypes = [...types];
|
||||
}
|
||||
for (const t of types) {
|
||||
absorbed.add(`${t.entryPoint}:${t.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Return items without the absorbed types
|
||||
return items.filter(item => !absorbed.has(`${item.entryPoint}:${item.name}`));
|
||||
}
|
||||
|
||||
// ── Package Extraction ─────────────────────────────────────────────────────
|
||||
|
||||
function extractPackage(config: PackageConfig): PackageMeta | null {
|
||||
const pkgDir = resolve(ROOT, config.path);
|
||||
const pkgJsonPath = resolve(pkgDir, 'package.json');
|
||||
|
||||
if (!existsSync(pkgJsonPath)) {
|
||||
console.warn(`[extractor] package.json not found: ${pkgJsonPath}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
|
||||
const exports = pkgJson.exports ?? {};
|
||||
|
||||
// Determine entry points
|
||||
const entryPoints: Array<{ subpath: string; filePath: string }> = [];
|
||||
|
||||
for (const [subpath, value] of Object.entries(exports)) {
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
const entry = (value as Record<string, string>).import ?? (value as Record<string, string>).types;
|
||||
if (entry) {
|
||||
// Map dist path back to source path
|
||||
// e.g. "./dist/index.js" → "src/index.ts" or "./dist/browsers.js" → "src/browsers/index.ts"
|
||||
const srcPath = entry
|
||||
.replace(/^\.\/dist\//, 'src/')
|
||||
.replace(/\.js$/, '.ts')
|
||||
.replace(/\.d\.ts$/, '.ts');
|
||||
|
||||
const fullPath = resolve(pkgDir, srcPath);
|
||||
if (existsSync(fullPath)) {
|
||||
entryPoints.push({ subpath, filePath: fullPath });
|
||||
} else {
|
||||
// Try index.ts in subdirectory
|
||||
const altPath = resolve(pkgDir, srcPath.replace(/\.ts$/, '/index.ts'));
|
||||
if (existsSync(altPath)) {
|
||||
entryPoints.push({ subpath, filePath: altPath });
|
||||
} else {
|
||||
console.warn(`[extractor] Entry point not found: ${fullPath} or ${altPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (entryPoints.length === 0) {
|
||||
console.warn(`[extractor] No entry points found for ${pkgJson.name}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Create ts-morph project for this package
|
||||
const tsconfigPath = resolve(pkgDir, 'tsconfig.json');
|
||||
const project = new Project({
|
||||
tsConfigFilePath: existsSync(tsconfigPath) ? tsconfigPath : undefined,
|
||||
skipAddingFilesFromTsConfig: true,
|
||||
});
|
||||
|
||||
// Add entry files
|
||||
for (const ep of entryPoints) {
|
||||
project.addSourceFileAtPath(ep.filePath);
|
||||
}
|
||||
|
||||
// Resolve all referenced files
|
||||
project.resolveSourceFileDependencies();
|
||||
|
||||
// Extract items from all entry points
|
||||
const allItems: ItemMeta[] = [];
|
||||
for (const ep of entryPoints) {
|
||||
const sourceFile = project.getSourceFile(ep.filePath);
|
||||
if (!sourceFile) continue;
|
||||
const items = collectExportedItems(sourceFile, ep.subpath);
|
||||
allItems.push(...items);
|
||||
}
|
||||
|
||||
// Deduplicate by name (overloaded functions may appear once already)
|
||||
const seen = new Set<string>();
|
||||
const uniqueItems = allItems.filter(item => {
|
||||
const key = `${item.entryPoint}:${item.name}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
|
||||
// Group co-located types with their parent class/function.
|
||||
// Types/interfaces from a types.ts file in the same directory as a
|
||||
// class or function become relatedTypes of that primary item.
|
||||
const groupedItems = groupCoLocatedTypes(uniqueItems);
|
||||
|
||||
// Group by category
|
||||
const categoryMap = new Map<string, ItemMeta[]>();
|
||||
for (const item of groupedItems) {
|
||||
// Infer category from source path if not set
|
||||
const jsdocCategory = inferCategoryFromItem(item);
|
||||
const existing = categoryMap.get(jsdocCategory) ?? [];
|
||||
existing.push(item);
|
||||
categoryMap.set(jsdocCategory, existing);
|
||||
}
|
||||
|
||||
const categories: CategoryMeta[] = Array.from(categoryMap.entries())
|
||||
.map(([name, items]) => ({
|
||||
name,
|
||||
slug: slugify(name),
|
||||
items: items.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
return {
|
||||
name: pkgJson.name,
|
||||
version: pkgJson.version,
|
||||
description: pkgJson.description ?? '',
|
||||
slug: config.slug,
|
||||
entryPoints: entryPoints.map(ep => ep.subpath),
|
||||
categories,
|
||||
};
|
||||
}
|
||||
|
||||
function inferCategoryFromItem(item: ItemMeta): string {
|
||||
// Parse from source path
|
||||
const parts = item.sourcePath.split('/src/');
|
||||
if (parts.length < 2) return 'General';
|
||||
|
||||
const segments = parts[1]!.split('/');
|
||||
|
||||
// Patterns:
|
||||
// composables/browser/useIntervalFn/index.ts → "Browser"
|
||||
// arrays/cluster/index.ts → "Arrays"
|
||||
// patterns/behavioral/PubSub/index.ts → "Patterns"
|
||||
// types/js/primitives.ts → "Types"
|
||||
// structs/Stack/index.ts → "Data Structures" (use @category if available)
|
||||
|
||||
if (segments[0] === 'composables' && segments.length >= 3) {
|
||||
const cat = segments[1]!;
|
||||
return cat.charAt(0).toUpperCase() + cat.slice(1);
|
||||
}
|
||||
|
||||
if (segments[0] && segments.length >= 2) {
|
||||
const cat = segments[0];
|
||||
return cat.charAt(0).toUpperCase() + cat.slice(1);
|
||||
}
|
||||
|
||||
return 'General';
|
||||
}
|
||||
|
||||
// ── Main ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function extract(): DocsMetadata {
|
||||
console.log('[extractor] Starting metadata extraction...');
|
||||
|
||||
const packages: PackageMeta[] = [];
|
||||
|
||||
for (const config of PACKAGES) {
|
||||
console.log(`[extractor] Processing ${config.path}...`);
|
||||
const pkg = extractPackage(config);
|
||||
if (pkg) {
|
||||
const itemCount = pkg.categories.reduce((sum, c) => sum + c.items.length, 0);
|
||||
console.log(`[extractor] → ${pkg.name}@${pkg.version}: ${itemCount} items in ${pkg.categories.length} categories`);
|
||||
packages.push(pkg);
|
||||
}
|
||||
}
|
||||
|
||||
const metadata: DocsMetadata = {
|
||||
packages,
|
||||
generatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const totalItems = packages.reduce(
|
||||
(sum, pkg) => sum + pkg.categories.reduce((s, c) => s + c.items.length, 0),
|
||||
0,
|
||||
);
|
||||
console.log(`[extractor] Done — ${totalItems} items across ${packages.length} packages`);
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
// Allow running directly — prints metadata as JSON to stdout
|
||||
if (import.meta.filename === process.argv[1]) {
|
||||
const metadata = extract();
|
||||
console.log(JSON.stringify(metadata, null, 2));
|
||||
}
|
||||
146
docs/modules/extractor/index.ts
Normal file
146
docs/modules/extractor/index.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Nuxt module that extracts TypeScript metadata from source packages
|
||||
* and provides it as a virtual module `#docs/metadata`.
|
||||
*
|
||||
* Runs extraction at build start and makes the data available to all
|
||||
* pages/components via `import metadata from '#docs/metadata'`.
|
||||
*/
|
||||
|
||||
import { defineNuxtModule, addTemplate, createResolver } from '@nuxt/kit';
|
||||
import { resolve, dirname } from 'node:path';
|
||||
import type { DocsMetadata } from './types';
|
||||
|
||||
export default defineNuxtModule({
|
||||
meta: {
|
||||
name: 'docs-extractor',
|
||||
configKey: 'docsExtractor',
|
||||
},
|
||||
|
||||
async setup(_options, nuxt) {
|
||||
const { resolve: resolveModule } = createResolver(import.meta.url);
|
||||
const ROOT = resolve(import.meta.dirname, '..', '..', '..');
|
||||
|
||||
// Run extraction immediately during setup so metadata is available
|
||||
// when templates are resolved (app:templates phase runs before build:before)
|
||||
console.log('[docs-extractor] Running metadata extraction...');
|
||||
const { extract } = await import('./extract');
|
||||
const metadata: DocsMetadata = extract();
|
||||
|
||||
// Add Vite resolve aliases for source packages so demo.vue imports resolve.
|
||||
// The web/vue package uses `@/` path aliases (e.g. `@/composables/...`).
|
||||
// We prepend them via vite:extendConfig so they take priority over Nuxt's
|
||||
// built-in `@` → srcDir alias.
|
||||
const vueSrc = resolve(ROOT, 'web/vue/src');
|
||||
|
||||
nuxt.hook('vite:extendConfig', (config) => {
|
||||
const existing = config.resolve?.alias;
|
||||
const sourceAliases = [
|
||||
{ find: '@/composables', replacement: resolve(vueSrc, 'composables') },
|
||||
{ find: '@/types', replacement: resolve(vueSrc, 'types') },
|
||||
{ find: '@/utils', replacement: resolve(vueSrc, 'utils') },
|
||||
];
|
||||
|
||||
if (Array.isArray(existing)) {
|
||||
existing.unshift(...sourceAliases);
|
||||
} else {
|
||||
config.resolve ??= {};
|
||||
config.resolve.alias = [
|
||||
...sourceAliases,
|
||||
...Object.entries(existing ?? {}).map(([find, replacement]) => ({ find, replacement: replacement as string })),
|
||||
];
|
||||
}
|
||||
});
|
||||
|
||||
// Provide metadata as a virtual template
|
||||
addTemplate({
|
||||
filename: 'docs-metadata.ts',
|
||||
write: true,
|
||||
getContents: () => {
|
||||
const json = JSON.stringify(metadata, null, 2);
|
||||
return `export default ${json} as const;`;
|
||||
},
|
||||
});
|
||||
|
||||
// Register the alias for the virtual module
|
||||
nuxt.options.alias['#docs/metadata'] = resolve(nuxt.options.buildDir, 'docs-metadata');
|
||||
|
||||
// Add types reference
|
||||
addTemplate({
|
||||
filename: 'docs-metadata-types.d.ts',
|
||||
write: true,
|
||||
getContents: () => {
|
||||
const typesPath = resolveModule('./types');
|
||||
return `
|
||||
import type { DocsMetadata } from '${typesPath}';
|
||||
declare module '#docs/metadata' {
|
||||
const metadata: DocsMetadata;
|
||||
export default metadata;
|
||||
}
|
||||
`;
|
||||
},
|
||||
});
|
||||
|
||||
// Register prerender routes from metadata
|
||||
nuxt.hook('prerender:routes', async ({ routes }: { routes: Set<string> }) => {
|
||||
if (metadata.packages.length === 0) return;
|
||||
|
||||
for (const pkg of metadata.packages) {
|
||||
routes.add(`/${pkg.slug}`);
|
||||
for (const category of pkg.categories) {
|
||||
for (const item of category.items) {
|
||||
routes.add(`/${pkg.slug}/${item.slug}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[docs-extractor] Registered ${routes.size} routes for prerender`);
|
||||
});
|
||||
|
||||
// Generate demo component import map
|
||||
addTemplate({
|
||||
filename: 'docs-demos.ts',
|
||||
write: true,
|
||||
getContents: () => {
|
||||
const entries: string[] = [];
|
||||
|
||||
for (const pkg of metadata.packages) {
|
||||
for (const cat of pkg.categories) {
|
||||
for (const item of cat.items) {
|
||||
if (item.hasDemo) {
|
||||
const demoPath = resolve(ROOT, dirname(item.sourcePath), 'demo.vue');
|
||||
entries.push(` '${pkg.slug}/${item.slug}': defineAsyncComponent(() => import('${demoPath}')),`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
return `import type { Component } from 'vue';\nexport const demos: Record<string, Component> = {};\n`;
|
||||
}
|
||||
|
||||
return [
|
||||
`import { defineAsyncComponent } from 'vue';`,
|
||||
`import type { Component } from 'vue';`,
|
||||
``,
|
||||
`export const demos: Record<string, Component> = {`,
|
||||
...entries,
|
||||
`};`,
|
||||
``,
|
||||
].join('\n');
|
||||
},
|
||||
});
|
||||
|
||||
nuxt.options.alias['#docs/demos'] = resolve(nuxt.options.buildDir, 'docs-demos');
|
||||
|
||||
addTemplate({
|
||||
filename: 'docs-demos-types.d.ts',
|
||||
write: true,
|
||||
getContents: () => `
|
||||
import type { Component } from 'vue';
|
||||
declare module '#docs/demos' {
|
||||
export const demos: Record<string, Component>;
|
||||
}
|
||||
`,
|
||||
});
|
||||
},
|
||||
});
|
||||
112
docs/modules/extractor/types.ts
Normal file
112
docs/modules/extractor/types.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* Metadata types for the documentation extractor.
|
||||
* These types represent the structured data extracted from source packages
|
||||
* via ts-morph, used to generate documentation pages.
|
||||
*/
|
||||
|
||||
export interface DocsMetadata {
|
||||
packages: PackageMeta[];
|
||||
generatedAt: string;
|
||||
}
|
||||
|
||||
export interface PackageMeta {
|
||||
/** Package name from package.json, e.g. "@robonen/stdlib" */
|
||||
name: string;
|
||||
/** Package version */
|
||||
version: string;
|
||||
/** Package description from package.json */
|
||||
description: string;
|
||||
/** URL-friendly slug derived from package name, e.g. "stdlib" */
|
||||
slug: string;
|
||||
/** Subpath export entries (e.g. "." or "./browsers") */
|
||||
entryPoints: string[];
|
||||
/** All documented items grouped by category */
|
||||
categories: CategoryMeta[];
|
||||
}
|
||||
|
||||
export interface CategoryMeta {
|
||||
/** Category name from @category JSDoc tag or directory name */
|
||||
name: string;
|
||||
/** URL-friendly slug */
|
||||
slug: string;
|
||||
/** Items in this category */
|
||||
items: ItemMeta[];
|
||||
}
|
||||
|
||||
export interface ItemMeta {
|
||||
/** Export name */
|
||||
name: string;
|
||||
/** URL-friendly slug (camelCase → kebab-case) */
|
||||
slug: string;
|
||||
/** Kind of export */
|
||||
kind: 'function' | 'class' | 'type' | 'interface' | 'enum' | 'variable';
|
||||
/** Description from @description tag or first JSDoc line */
|
||||
description: string;
|
||||
/** Version when this item was introduced */
|
||||
since: string;
|
||||
/** Full TypeScript signature(s) — supports overloads */
|
||||
signatures: string[];
|
||||
/** Function/method parameters */
|
||||
params: ParamMeta[];
|
||||
/** Return type description */
|
||||
returns: ReturnMeta | null;
|
||||
/** Template/generic type parameters */
|
||||
typeParams: TypeParamMeta[];
|
||||
/** Code examples from @example tags */
|
||||
examples: string[];
|
||||
/** Class methods (only for kind === 'class') */
|
||||
methods: MethodMeta[];
|
||||
/** Class/interface properties (only for kind === 'class' or 'interface') */
|
||||
properties: PropertyMeta[];
|
||||
/** Whether a demo.vue file exists alongside */
|
||||
hasDemo: boolean;
|
||||
/** Raw source code of the demo.vue file (for syntax-highlighted display) */
|
||||
demoSource: string;
|
||||
/** Whether an index.test.ts file exists alongside */
|
||||
hasTests: boolean;
|
||||
/** Related types/interfaces co-located in the same module directory */
|
||||
relatedTypes: ItemMeta[];
|
||||
/** Relative path to the source file from repo root */
|
||||
sourcePath: string;
|
||||
/** Subpath export this belongs to (e.g. "." or "./browsers") */
|
||||
entryPoint: string;
|
||||
}
|
||||
|
||||
export interface ParamMeta {
|
||||
name: string;
|
||||
type: string;
|
||||
description: string;
|
||||
optional: boolean;
|
||||
defaultValue: string | null;
|
||||
}
|
||||
|
||||
export interface ReturnMeta {
|
||||
type: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface TypeParamMeta {
|
||||
name: string;
|
||||
constraint: string | null;
|
||||
default: string | null;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface MethodMeta {
|
||||
name: string;
|
||||
description: string;
|
||||
signatures: string[];
|
||||
params: ParamMeta[];
|
||||
returns: ReturnMeta | null;
|
||||
/** Visibility: public, protected, private */
|
||||
visibility: string;
|
||||
}
|
||||
|
||||
export interface PropertyMeta {
|
||||
name: string;
|
||||
type: string;
|
||||
description: string;
|
||||
optional: boolean;
|
||||
defaultValue: string | null;
|
||||
readonly: boolean;
|
||||
}
|
||||
53
docs/nuxt.config.ts
Normal file
53
docs/nuxt.config.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
|
||||
export default defineNuxtConfig({
|
||||
future: {
|
||||
compatibilityVersion: 4,
|
||||
},
|
||||
|
||||
modules: [
|
||||
'@nuxt/fonts',
|
||||
'./modules/extractor',
|
||||
],
|
||||
|
||||
vite: {
|
||||
plugins: [
|
||||
tailwindcss() as any,
|
||||
],
|
||||
},
|
||||
|
||||
css: ['~/assets/css/main.css'],
|
||||
|
||||
ssr: true,
|
||||
|
||||
routeRules: {
|
||||
'/**': { prerender: true },
|
||||
},
|
||||
|
||||
nitro: {
|
||||
prerender: {
|
||||
crawlLinks: true,
|
||||
},
|
||||
},
|
||||
|
||||
fonts: {
|
||||
families: [
|
||||
{ name: 'Inter', provider: 'google', weights: [400, 500, 600, 700] },
|
||||
{ name: 'JetBrains Mono', provider: 'google', weights: [400, 500] },
|
||||
],
|
||||
},
|
||||
|
||||
app: {
|
||||
head: {
|
||||
title: '@robonen/tools — Documentation',
|
||||
meta: [
|
||||
{ name: 'description', content: 'Auto-generated documentation for @robonen/tools monorepo' },
|
||||
],
|
||||
htmlAttrs: {
|
||||
lang: 'en',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
compatibilityDate: '2026-02-15',
|
||||
});
|
||||
29
docs/package.json
Normal file
29
docs/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@robonen/docs",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"description": "Auto-generated documentation site for @robonen/tools",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nuxt dev",
|
||||
"build": "nuxt build",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"extract": "jiti ./modules/extractor/extract.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"shiki": "^3.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nuxt/fonts": "^0.11.4",
|
||||
"@nuxt/kit": "^4.3.1",
|
||||
"@tailwindcss/vite": "^4.1.0",
|
||||
"jiti": "^2.6.1",
|
||||
"nuxt": "catalog:",
|
||||
"tailwindcss": "^4.1.0",
|
||||
"ts-morph": "^25.0.0",
|
||||
"vue": "catalog:",
|
||||
"vue-router": "^4.5.1"
|
||||
}
|
||||
}
|
||||
3
docs/tsconfig.json
Normal file
3
docs/tsconfig.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./.nuxt/tsconfig.json"
|
||||
}
|
||||
Reference in New Issue
Block a user