Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Content Collection injection #135

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .changeset/blue-seals-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
"astro-theme-provider": minor
---

Added the ability for themes to seed content collections and inject schemas into a user's project using [`@inox-tools/content-utils`](https://www.npmjs.com/package/@inox-tools/content-utils), thanks [@Fryuni](https://github.com/Fryuni)!

```
package/
└── src/
└── content/
├── myBlog/
│ └── example.md
└── config.ts
```

```ts
// package/src/content/config.ts

import { z, defineCollection } from 'my-theme:content';

export const collections = {
myBlog: defineCollection({
schema: z.object({
title: z.string()
})
})
}
```

All collection schemas defined inside `package/src/content/config.ts` are injected into a user's project.

All collection directories inside `package/src/content/` will be copied to a user's project if the collection directory does not exist
2 changes: 1 addition & 1 deletion .changeset/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": ["docs", "playground", "theme-playground", "theme-ssg", "test-e2e-ssg"]
"ignore": ["playground", "theme-playground", "theme-ssg", "test-e2e-ssg"]
}
4 changes: 2 additions & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
},
"dependencies": {
"@astrojs/check": "^0.7.0",
"@astrojs/starlight": "^0.24.1",
"astro": "^4.10.1",
"@astrojs/starlight": "^0.24.3",
"astro": "^4.10.3",
"sharp": "^0.33.4"
}
}
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "root",
"private": true,
"packageManager": "pnpm@9.1.4",
"packageManager": "pnpm@9.4.0",
"engines": {
"node": ">=18.19.0"
},
Expand All @@ -21,9 +21,9 @@
},
"license": "MIT",
"devDependencies": {
"@biomejs/biome": "^1.8.0",
"@biomejs/biome": "^1.8.1",
"@changesets/cli": "^2.27.5",
"@playwright/test": "^1.44.1",
"astro": "^4.10.1"
"astro": "^4.10.3"
}
}
8 changes: 5 additions & 3 deletions package/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"files": ["dist"],
"peerDependencies": {
"@astrojs/db": ">=0.8.0",
"@inox-tools/content-utils": ">=0.2.1",
"astro": ">=3"
},
"peerDependenciesMeta": {
Expand All @@ -35,12 +36,13 @@
}
},
"devDependencies": {
"@astrojs/db": "^0.11.4",
"@types/node": "^20.14.2",
"@astrojs/db": "^0.11.6",
"@inox-tools/content-utils": "^0.4.0",
"@types/node": "^20.14.6",
"playwright": "^1.44.1",
"tsup": "^8.1.0",
"typescript": "^5.4.5",
"vite": "^5.2.13"
"vite": "^5.3.1"
},
"dependencies": {
"astro-integration-kit": "^0.13.3",
Expand Down
64 changes: 51 additions & 13 deletions package/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { existsSync } from "node:fs";
import { basename, extname, join, resolve } from "node:path";
import { injectCollections } from "@inox-tools/content-utils";
import type { AstroIntegration } from "astro";
import { addDts, addIntegration, addVitePlugin, watchDirectory } from "astro-integration-kit";
import { addPageDir } from "astro-pages";
Expand Down Expand Up @@ -46,6 +47,7 @@ export default function <ThemeName extends string, Schema extends z.ZodTypeAny>(
srcDir: themeSrc = "src",
pageDir = "pages",
publicDir = "public",
contentDir = "content",
middlewareDir = "./",
imports: themeImports = {},
integrations: themeIntegrations = [],
Expand All @@ -55,9 +57,21 @@ export default function <ThemeName extends string, Schema extends z.ZodTypeAny>(

const themeRoot = resolveDirectory("./", themeEntrypoint);

themeSrc = resolveDirectory(themeRoot, themeSrc);

const themePackage = new PackageJSON(themeRoot);

themeSrc = resolveDirectory(themeRoot, themeSrc);
let contentConfig: string | null = null;

if (contentDir) {
contentDir = resolveDirectory(themeSrc, contentDir, false);
if (contentDir) {
contentConfig =
["config.mjs", "config.js", "config.mts", "config.ts"]
.map((configPath) => resolve(contentDir || "./", configPath))
.find((configPath) => existsSync(configPath)) || null;
}
}

if (middlewareDir) {
middlewareDir = resolveDirectory(themeSrc, middlewareDir);
Expand Down Expand Up @@ -116,31 +130,33 @@ export default function <ThemeName extends string, Schema extends z.ZodTypeAny>(
"astro:config:setup": (params) => {
const { config, logger, injectRoute, addMiddleware } = params;

// Root of a user's project (directory that contains the Astrto config)
const projectRoot = resolveDirectory("./", config.root);

// Record of virtual imports and their content
// Record of virtual modules
const virtualImports: Parameters<typeof createVirtualResolver>[0]["imports"] = {
[`${themeName}:config`]: `export default ${JSON.stringify(userConfig)}`,
[`${themeName}:context`]: "",
[`${themeName}:config`]: `export default ${JSON.stringify(userConfig)}`,
};

// Type buffers for declaring interfaces: `declare interface ThemeExports { ... }`
const interfaceBuffers: Record<string, string> = {
ThemeExports: "",
ThemeRoutes: "",
ThemeIntegrations: "",
ThemeIntegrationsResolved: "",
};

// Module type buffers
// Type buffers for declaring modules: `declare module "my-theme:config" { ... }`
const moduleBuffers: Record<string, string> = {
[`${themeName}:context`]: "",
[`${themeName}:config`]: `
const config: NonNullable<NonNullable<Parameters<typeof import("${themeEntrypoint}").default>[0]>["config"]>;
export default config;
`,
[`${themeName}:context`]: "",
};

// Interface type buffers
const interfaceBuffers = {
ThemeExports: "",
ThemeRoutes: "",
ThemeIntegrations: "",
ThemeIntegrationsResolved: "",
};

// Template/stub for type generation
let themeTypesBuffer = `
type ThemeName = "${themeName}";

Expand Down Expand Up @@ -248,6 +264,28 @@ export default function <ThemeName extends string, Schema extends z.ZodTypeAny>(
}
}

// Inject collections
if (contentConfig) {
// Create virtual import used by author to define collections
virtualImports[`${themeName}:content`] = `
export * from "astro:content";
export { defineCollection } from "@it-astro:content";
`;
moduleBuffers[`${themeName}:content`] = `
export * from "astro:content";
export { defineCollection } from "@it-astro:content";
`;
// Create virtual import used to inject and override collections
virtualImports[`${themeName}:collections`] = `export * from ${JSON.stringify(contentConfig)}`;
moduleBuffers[`${themeName}:collections`] =
`export const collections: typeof import(${JSON.stringify(contentConfig)}).collections;`;
// Inject the content collections
injectCollections(params, {
entrypoint: `${themeName}:collections`,
seedTemplateDirectory: contentDir as string,
});
}

// Reserved names for built-in virtual modules
const reservedNames = new Set(["config", "context", "content", "collections", "db"]);

Expand Down
1 change: 1 addition & 0 deletions package/src/internal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type AuthorOptions<ThemeName extends string, Schema extends z.ZodTypeAny>
srcDir?: string;
pageDir?: PageDirOption | string;
publicDir?: StaticDirOption | string | false | null | undefined;
contentDir?: string | false | null | undefined;
middlewareDir?: string | false | null | undefined;
log?: "verbose" | "minimal" | boolean;
schema?: Schema;
Expand Down
2 changes: 1 addition & 1 deletion package/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default defineConfig((options) => {
sourcemap: true,
clean: true,
splitting: true,
noExternal: ["astro-pages", "astro-public"],
noExternal: ["astro-public"],
minify: !dev,
external: [...Object.keys(peerDependencies)],
tsconfig: "tsconfig.build.json",
Expand Down
4 changes: 2 additions & 2 deletions playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"astro": "astro"
},
"dependencies": {
"@astrojs/sitemap": "^3.1.5",
"astro": "^4.10.1",
"@astrojs/sitemap": "^3.1.6",
"astro": "^4.10.3",
"astro-integration-kit": "^0.13.3",
"sharp": "^0.33.4",
"theme-playground": "workspace:^"
Expand Down
3 changes: 3 additions & 0 deletions playground/src/CustomHeading.astro
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
---
import { Heading } from "theme-playground:components";
import { getCollection } from "theme-playground:content";

console.log(await getCollection("blog"));
---

<Heading>
Expand Down
7 changes: 7 additions & 0 deletions playground/src/content/blog/one.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
title: One
---

This file was seeded from `theme-playground`

[Blog](/blog) | [Two](/blog/two)
8 changes: 8 additions & 0 deletions playground/src/content/blog/three.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
title: Three
---

This file was seeded from `theme-playground`


[Blog](/blog) | [One](/blog/one)
7 changes: 7 additions & 0 deletions playground/src/content/blog/two.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
title: Two
---

This file was seeded from `theme-playground`

[Blog](/blog) | [Three](/blog/three)
8 changes: 8 additions & 0 deletions playground/src/content/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineCollection, z } from "astro:content";
import { collections as themeCollections } from "theme-playground:collections";

export const collections = {
// blog: defineCollection({
// schema: z.object({})
// })
};
1 change: 1 addition & 0 deletions playground/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
/// <reference types="../.astro/types.d.ts" />
/// <reference types="../.astro/theme-playground.d.ts" />
3 changes: 2 additions & 1 deletion playground/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"extends": "astro/tsconfigs/strictest"
"extends": "astro/tsconfigs/strictest",
"exclude": ["../docs/**/*", "../tests/**/*", "../package/**/*"]
}
Loading