# Content from code

Write pages, entries, globals and images from a script instead of the admin: to seed a new site, or to move a client's old content in. At the end you have a script you can run again after it stops halfway.

## Where it runs

**Astro**

`createContent(config)` from `smoodly/astro` builds the content API for a script. It reads `.env` and posts to Smoodly's API with the secret key, which runs the same operations as the admin, with no editor signed in. So every rule the admin enforces holds for a script too: required fields, slug rules, the checks before a publish. It needs the secret key, so it runs on the server only: in a script or an endpoint.

The starter's own content is written this way:

File: `scripts/seed.ts`

```ts
const { config } = await import("../src/smoodly/config");
// …
const { node } = await import("smoodly");
const { createContent } = await import("smoodly/astro");
const { content, href } = createContent(config);
```

`href` turns a path in one language into the site's URL, on the same rules as the site. When `astro.config.ts` sets `i18n`, pass the same object: `createContent(config, { i18n })`. The samples below use `c` for the content API; a script of yours starts like this:

```ts
import { node } from "smoodly";
import { createContent } from "smoodly/astro";
import { config } from "@/smoodly/config";

const { content: c } = createContent(config);
```

Add a line to `package.json` for it, and run it with `npm run`, from the project's folder:

File: `package.json`

```json
{
  "scripts": {
    "services": "tsx scripts/services.ts"
  }
}
```

```bash
npm run services
```

The samples below import from `@/smoodly/server`, the Next.js file; in an Astro script those lines are the three above. Two things about such a script: `astro check` reads it, and a file with a top-level `await` must be a module, which any `import` line at the top makes it; and `@/` resolves from the project's folder, so run it through `npm run`, not `tsx` from elsewhere.

**Next.js**

`smoodly/server.ts` exports `content()`. It posts to Smoodly's API with the secret key, which runs the same operations as the admin, with no editor signed in, so every rule the admin enforces holds for a script too: required fields, slug rules, the checks before a publish. It needs the secret key, so it runs on the server only: in a script, a route handler or a server action. A script that uses a section, an element or a field you just added needs the schema pushed first: a dev server or a build pushes it when it starts, and `npx smoodly push` does it on its own; until then the service refuses the publish, naming the type the space does not know yet.

The starter's own content is written this way. `scripts/seed.ts` loads `.env.local`, then takes `content()`:

File: `scripts/seed.ts`

```ts
import next from "@next/env";
// …
const { loadEnvConfig } = next;

loadEnvConfig(process.cwd());
// …
const { content, href, node } = await import("../smoodly/server");
// …
const c = content();
```

`content()` reads the keys when it is called, not when `smoodly/server` is imported, so a script of your own can import it at the top and call `loadEnvConfig` first. Add a line to `package.json` for it, and run it with `npm run`, from the project's folder:

File: `package.json`

```json
{
  "scripts": {
    "services": "tsx scripts/services.ts"
  }
}
```

```bash
npm run services
```

## A page

A page is created in one language, given its sections, and published. `node()` builds a section for the tree: its fields are typed from the section's own definition, so a wrong field name fails in your editor. The function below finds the page before it creates it, so it can run again; the last section says why each step is safe to repeat.

File: `scripts/services.ts`

```ts
import next from "@next/env";
import { SmoodlyContentError } from "smoodly/admin";
import { content, node } from "@/smoodly/server";
import { pageHeroSchema } from "@/components/sections/PageHero.schema";
import { pointsSchema } from "@/components/sections/Points.schema";

next.loadEnvConfig(process.cwd());
const c = content();

async function servicesPage() {
  const page =
    (await c.pages.find("en", "/services")) ??
    (await c.pages.create({ parentId: null, locale: "en", slug: "services", template: "page", title: "Services" }));
  await c.pages.setTree(page.id, "en", {
    zones: {
      hero: [node(pageHeroSchema, { heading: "Services", text: "What we do for our clients." })],
      body: [node(pointsSchema, { heading: "Three things", points: [{ icon: "circle", heading: "Design", text: "Sites that read well." }] })],
    },
  });
  await c.pages.publish(page.id, "en");
  // The Finnish page starts as a copy of the English one, at its own slug.
  if (!page.locales.fi) await c.pages.addLocale(page.id, "fi", { from: "en", slug: "palvelut", title: "Palvelut" });
  await c.pages.publish(page.id, "fi");
  return page;
}
```

The example is the multilingual Lorem Co. starter's: on a one-language site leave out the Finnish lines, and on Blank the Page type has a `body` zone only. `hero` and `body` are the zones of the starter's Page type, and each takes the sections its zone lists. The Finnish page holds the English text until `setTree(page.id, "fi", …)` gives it its own. `template` is the page type's `name`, and `parentId` is another page's id, or `null` for the top level. `getTree(id, locale)` reads a page's draft back, for a script that changes a page instead of replacing it. `pages.list({ locale, template })` gives every page in a language, folders left out, for a script that changes many:

File: `scripts/rename.ts`

```ts
import next from "@next/env";
import { content } from "@/smoodly/server";

next.loadEnvConfig(process.cwd());
const c = content();

for (const page of await c.pages.list({ template: "page" })) {
  const tree = await c.pages.getTree(page.id, "en");
  // …change the tree, then:
  if (tree) await c.pages.setTree(page.id, "en", tree);
}
```

Every call throws a `SmoodlyContentError` when the admin would have refused it. It comes from `smoodly/admin`, which is server code: a script may import it, the site's pages and sections never do. The error carries a `code` and, for a publish that failed validation, one line per field:

File: `scripts/services.ts`

```ts
async function run(step: () => Promise<unknown>) {
  try {
    await step();
  } catch (error) {
    if (!(error instanceof SmoodlyContentError)) throw error;
    console.error(error.code, error.message);
    for (const field of error.fields) console.error(field.field, field.message);
    process.exit(1);
  }
}
```

The draft stays as the script left it, so you can fix the content and run the publish again.

## Entries, globals and images

An entry is created with its fields, then published. A localized field gets its other language with `addLocale`. A reference is stored as the other entry's id, so pass `person.id` where a field is an `f.ref()`. A slug that follows another field, `f.slug({ from: "title" })`, is filled from it when you leave it out, as the admin's form does; pass `slug` to choose your own.

An `f.richtext()` value is the editor's own document, TipTap JSON: a `doc` holding paragraphs, headings and lists, each holding text. A required richtext field left out is a *Required* error on publish:

File: `scripts/services.ts`

```ts
const text = (t: string) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: t }] }] });
await c.entries.create("recipes", { locale: "en", fields: { title: "Fish stew", body: text("Serves four.") } });
```

File: `scripts/services.ts`

```ts
async function person() {
  const aino = await c.entries.create("people", { locale: "en", fields: { name: "Aino Virtanen", role: "Designer" } });
  await c.entries.addLocale("people", aino.id, "fi", { from: "en", fields: { name: "Aino Virtanen", role: "Muotoilija" } });
  await c.entries.publish("people", aino.id, "en");
  await c.entries.publish("people", aino.id, "fi");
  return aino;
}
```

A global exists once, so there is nothing to create: `set` writes its fields and `publish` makes them live. Until the publish the change is a draft: the live site shows the old fields, draft mode shows the new ones, which is a quick way to try a preview link.

File: `scripts/services.ts`

```ts
async function contactDetails() {
  await c.globals.set("contact", "en", { email: "hello@example.com", address: "Main Street 1, Helsinki" });
  await c.globals.publish("contact", "en");
}
```

`media.upload()` takes a file path or bytes and puts the file in the media library. The admin's rules apply: an accepted file type and the size limit from `media` in the config. It returns the value an `f.image()` field stores, so it goes straight into a node or an entry:

File: `scripts/services.ts`

```ts
async function teamPage() {
  const photo = await c.media.upload("public/images/about_main.jpg", { alt: "The team at work" });
  const page = await c.pages.create({ parentId: null, locale: "en", slug: "team", template: "page", title: "Team" });
  await c.pages.setTree(page.id, "en", {
    zones: { hero: [node(pageHeroSchema, { heading: "Our team", text: "The people you will work with.", image: photo })] },
  });
  await c.pages.publish(page.id, "en");
}
```

## Run it twice

A script that stops halfway, on a validation error or a dropped connection, gets run again. Each step above is safe to repeat, or guarded:

- `pages.find(locale, path)` returns the page at that URL, a draft included, or `null`. Finding before creating makes the page once.
- `setTree`, `globals.set` and `publish` replace what is there, so a second run leaves the same result.
- `addLocale` refuses a language the page already has, so check `page.locales` first.
- `entries.find(collection, { slug })` finds an entry by its slug, in the default language unless you pass a `locale`.
- `entries.list(collection, { where })` lists the entries whose fields match, for a collection without a slug field, such as the starter's people. A field holding a list, such as tags, matches when it holds the value:

File: `scripts/services.ts`

```ts
const [existing] = await c.entries.list("people", { where: { name: "Aino Virtanen" } });
const aino = existing ?? (await person());
```
- Every `media.upload` adds a file to the library. Upload where the thing that uses it is created, once.

File: `scripts/services.ts`

```ts
await run(async () => {
  const hadTeam = (await c.pages.find("en", "/team")) !== null;
  await servicesPage();
  await contactDetails();
  // The team page, its photo and its person are made together, on the first run only.
  if (!hadTeam) {
    await person();
    await teamPage();
  }
});
```

## Code-owned pages

A fixed page type, such as Home or a collection's list page, has its URL in code. It is live as soon as the code is deployed, with empty zones, and you never create it. `find` returns its record, making it first when the space is new. Then you fill it like any page:

File: `scripts/services.ts`

```ts
async function articlesList() {
  const list = await c.pages.find("en", "/posts");
  if (!list) return;
  await c.pages.setTree(list.id, "en", { zones: { hero: [node(pageHeroSchema, { heading: "Articles", text: "What we have been writing." })] } });
  await c.pages.publish(list.id, "en");
}
```

Its title and slug stay what the page type says, in every language.

## Members

Who can sign in to the admin is not set from code. A space's member list is kept at smoodly.io and arrives in the space whole; the admin's Settings › Members page shows it and links there.

Next, [the admin](https://smoodly.io/docs/getting-started/admin) is where editors take over from here.
