# @tryghost/mg-utils

> Shared utilities for the Ghost migration tooling.

Latest version **0.11.6** (published 2026-08-24) · MIT license · 0 weekly downloads

## Install

```sh
npm install @tryghost/mg-utils
pnpm add @tryghost/mg-utils
yarn add @tryghost/mg-utils
bun add @tryghost/mg-utils
```

## Health

**Score 75/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score; high quality score.

Warnings: low downloads; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.11.6 |
| Published | 2026-08-24 |
| First published | 2026-03-11 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM |
| Dependencies | 3 |
| Unpacked size | 53 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 69 |
| Author | Ghost Foundation |
| Maintainers | zimoatghost, allouis, kernalghost, chrisraible, erisds, johnonolan, kevinansfield, cobbspur, aileencgn, jloh, minimaluminium, sam-lord, pauladamdavis, bobvaneck, joeegrigg, hadret, erik-ghost, sagzy, vershwal, zach1618, mike182uk, luissazevedo, lsinger, nickmoreton, renatoworks, rblstr-ghost, evanhahn-ghost, austin.burdine, weylandswart, ghost-slimer, tmciesco, jonatan-ghost, 9larsons |

## Links

- npm: https://www.npmjs.com/package/@tryghost/mg-utils
- Repository: https://github.com/TryGhost/migrate
- Homepage: https://github.com/TryGhost/migrate#readme
- Issues: https://github.com/TryGhost/migrate/issues
- npm.io page: https://npm.io/package/@tryghost/mg-utils

## Dependencies (3)

- [linkedom](https://npm.io/package/linkedom.md) 0.18.13
- [fast-xml-parser](https://npm.io/package/fast-xml-parser.md) 5.10.1
- [@tryghost/kg-default-cards](https://npm.io/package/@tryghost/kg-default-cards.md) 10.3.5

## Recent versions

- 0.11.6 (latest) — 2026-08-24
- 0.11.5 — 2026-08-19
- 0.11.4 — 2026-08-12
- 0.11.3 — 2026-08-04
- 0.11.2 — 2026-07-15
- 0.11.1 — 2026-07-01
- 0.11.0 — 2026-06-17
- 0.10.0 — 2026-06-04
- 0.9.0 — 2026-05-07
- 0.8.3 — 2026-04-28
- 0.8.2 — 2026-04-28
- 0.8.1 — 2026-04-24
- 0.8.0 — 2026-04-20
- 0.7.0 — 2026-04-16
- 0.6.0 — 2026-04-10
- … 7 more at https://npm.io/package/@tryghost/mg-utils/versions

## README

# Migrate Utils

Shared utilities for the Ghost migration tooling.

## Install

To use this package in your own project:

`npm install @tryghost/mg-utils --save`

or

`pnpm add @tryghost/mg-utils`


## Usage

### DOM Utilities

Lightweight HTML parsing and manipulation powered by [linkedom](https://github.com/WebReflection/linkedom). Use `processFragment` for most cases — it parses HTML, passes the fragment to your callback, and automatically cleans up:

```js
import {domUtils} from '@tryghost/mg-utils';

const {processFragment, processFragmentAsync} = domUtils;

// Parse, manipulate, and get the result in one step
const html = processFragment('<p>Hello</p><p class="remove">World</p>', (parsed) => {
    for (const el of parsed.$('.remove')) {
        el.remove();
    }
    return parsed.html();
});
// => '<p>Hello</p>'

// Extract data from HTML
const title = processFragment(rawHtml, parsed => parsed.$('h1')[0]?.textContent || '');

// Async version for callbacks that need to await
const result = await processFragmentAsync(html, async (parsed) => {
    for (const img of parsed.$('img')) {
        const newSrc = await processImage(img.getAttribute('src'));
        img.setAttribute('src', newSrc);
    }
    return parsed.html();
});
```

The `parsed` fragment provides:
- **`parsed.$(selector, context?)`** — query elements (returns `Element[]`)
- **`parsed.html()`** — serialize the fragment back to an HTML string
- **`parsed.text()`** — get text content
- **`parsed.document`** — access the underlying `Document`
- **`parsed.body`** — access the `<body>` element

For long-lived or complex processing where a callback doesn't fit, use `parseFragment` directly:

```js
const {parseFragment} = domUtils;

const parsed = parseFragment(html);
// ... extensive manipulation ...
const result = parsed.html();
```

### DOM Manipulation Helpers

```js
const {replaceWith, insertBefore, insertAfter, wrap, createElement, attr} = domUtils;

const parsed = parseFragment('<div><p>Old</p></div>');
const p = parsed.$('p')[0];

replaceWith(p, '<span>New</span>');        // Replace element with HTML string or Node
insertBefore(el, '<!--kg-card-begin-->');   // Insert before element
insertAfter(el, '<!--kg-card-end-->');      // Insert after element
wrap(el, '<figure></figure>');              // Wrap element in a new parent

const div = createElement(parsed.document, 'div', {class: 'wrapper'});

attr(el, 'href');                // Get attribute (returns '' if missing)
attr(el, 'href', '/new-url');   // Set attribute
```

### Additional Element Utilities

- **`is(el, selector)`** — check if element matches a CSS selector
- **`parents(el, selector?)`** — get all parent elements, optionally filtered
- **`lastParent(el, selector)`** — get the furthest parent matching selector
- **`setStyle(el, property, value)`** — set a CSS style property
- **`isComment(node)`** / **`getCommentData(node)`** — comment node helpers
- **`serializeNode(node)`** / **`serializeChildren(node)`** — HTML5-compliant serialization

### XML Utilities

Parse XML strings or files into JavaScript objects using `fast-xml-parser`:

```js
import {xmlUtils} from '@tryghost/mg-utils';

const {parseXml} = xmlUtils;

// Parse an XML string
const data = await parseXml('<root><item>hello</item></root>');

// Parse from a file path
const data = await parseXml('/path/to/file.xml');

// Override parser options
const data = await parseXml(xmlString, {attributeNamePrefix: ''});
```


## Develop

This is a mono repository, managed with [Nx](https://nx.dev/) and pnpm workspaces.

Follow the instructions for the top-level repo.
1. `git clone` this repo & `cd` into it as usual
2. Run `pnpm install` to install top-level dependencies.


## Test

- `pnpm test` runs the package tests
- Linting and formatting are run from the repo root (`pnpm lint`, `pnpm format`)


# Copyright & License

Copyright (c) 2013-2026 Ghost Foundation - Released under the [MIT license](LICENSE).

---
_Source: https://npm.io/package/@tryghost/mg-utils · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
