mirror of
https://github.com/jackyzha0/quartz
synced 2026-11-30 22:44:41 +01:00
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d9b3c1f17d | ||
|
|
a024429fdf | ||
|
|
e5db91fd27 | ||
|
|
01c4d880c9 | ||
|
|
31975523c0 | ||
|
|
ad10a986be | ||
|
|
25efcce682 | ||
|
|
724d70a631 | ||
|
|
706b6fd30a | ||
|
|
5609393b17 | ||
|
|
6487fc2415 | ||
|
|
87ee900f05 | ||
|
|
92ff583098 | ||
|
|
c92fed97c0 | ||
|
|
79d3ea9875 | ||
|
|
f2015a4c76 | ||
|
|
2e69d52f76 | ||
|
|
8c81436188 | ||
|
|
fe47fb1239 | ||
|
|
fb4dbab487 | ||
|
|
9ca6f4ee69 | ||
|
|
cc8d104cc7 | ||
|
|
b86276f52b | ||
|
|
9ebfc67c1b | ||
|
|
efcb6e007e | ||
|
|
ffc6bfd3ed | ||
|
|
ea4b07518c | ||
|
|
afebc38b3b | ||
|
|
c7131c909f | ||
|
|
5a740b3ae0 | ||
|
|
6f67702b3e | ||
|
|
685a5c3461 | ||
|
|
114923ac6a | ||
|
|
a7d7389f57 | ||
|
|
699c668cba | ||
|
|
9889d3fb04 | ||
|
|
c68a4945ab | ||
|
|
ce108c8c95 | ||
|
|
57b3b5d0af | ||
|
|
c317915450 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
A plugin that depends on a plugin of another pipeline stage (an emitter or component on a transformer) no longer fails the build because of their `order`: order is checked only between plugins of the same stage.
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Plugin updates with the fixes from a test audit:
|
||||
|
||||
- note-properties: an empty `tags:` or `aliases:` no longer fails the build.
|
||||
- bases-page: sorting, filters, formulas and group headings work as in Obsidian.
|
||||
- encrypted-pages: a numeric `password` encrypts the page, and a custom `outputPath` works.
|
||||
- darkmode, reader-mode, syntax-highlighting and comments: no double handlers after a page is unlocked.
|
||||
- stacked-pages: links work under a base path.
|
||||
- breadcrumbs: `resolveFrontmatterTitle` is honoured.
|
||||
- canvas-page: a `#View` link selects that view.
|
||||
- search: fields left out of `fieldPriority` are searched, and excerpts keep their last word.
|
||||
- explorer: a note next to a folder of the same name stays listed, and folder options apply.
|
||||
- folder-page, og-image, description, table-of-contents, graph, obsidian-flavored-markdown and utils: smaller fixes.
|
||||
- latex: `customMacros` work with MathJax. ox-hugo: figure parameters in backticks.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
Relative links and embeds keep their query string after SPA navigation and in popovers (`./viewer.html?file=a.pdf` no longer loses `?file=a.pdf`).
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@jackyzha0/quartz": patch
|
||||
---
|
||||
|
||||
utils 1.3.4: inline `#tag` links from notes two or more folders deep stay under the site's base path. They went to `/tags/…` instead of `/<base>/tags/…`, a 404 on sites served under a sub-path such as GitHub Pages project sites.
|
||||
@@ -64,27 +64,3 @@ jobs:
|
||||
run: |
|
||||
npx changeset status --since=origin/v5 >/dev/null 2>&1 \
|
||||
|| echo "::warning::No changeset in this PR. If it changes how Quartz behaves, run 'npx changeset' (see .changeset/README.md)."
|
||||
|
||||
publish-tag:
|
||||
if: ${{ github.repository == 'jackyzha0/quartz' && github.ref == 'refs/heads/v5' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
- name: Get package version
|
||||
run: node -p -e '`PACKAGE_VERSION=${require("./package.json").version}`' >> $GITHUB_ENV
|
||||
- name: Create release tag
|
||||
uses: pkgdeps/git-tag-action@v3
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
github_repo: ${{ github.repository }}
|
||||
version: ${{ env.PACKAGE_VERSION }}
|
||||
git_commit_sha: ${{ github.sha }}
|
||||
git_tag_prefix: "v"
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
network=host
|
||||
- name: Install cosign
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: sigstore/cosign-installer@v4.1.3
|
||||
uses: sigstore/cosign-installer@v4.1.4
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v4
|
||||
if: github.event_name != 'pull_request'
|
||||
|
||||
@@ -85,6 +85,8 @@ jobs:
|
||||
# Letting `gh release create` make the tag instead gives an unsigned annotated tag
|
||||
# object (tagger: whoever merged the release PR), which GitHub marks "Unverified"
|
||||
# (jackyzha0/quartz#2455). `git describe --tags` reads lightweight tags as well.
|
||||
# This is the only place that tags a release: ci.yaml's old `publish-tag` job (an annotated
|
||||
# tag through pkgdeps/git-tag-action) ran first and kept every release tag unverified.
|
||||
if [ -z "$EXISTING" ]; then
|
||||
gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref="refs/tags/$TAG" -f sha="$GITHUB_SHA" >/dev/null
|
||||
else
|
||||
|
||||
@@ -1,5 +1,54 @@
|
||||
# @jackyzha0/quartz
|
||||
|
||||
## 5.4.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 724d70a: Links resolve against pages before aliases, as in Obsidian, where aliases aren't link targets: `[[upgrading]]` reaches the note `getting-started/upgrading.md` even when another address `upgrading` is an alias, and a note named like an alias wins over it. A link that only an alias matches now goes straight to the page with the alias, so its `#anchor` works (the alias's redirect page dropped it), and backlinks and the graph count it as a link to that page. Aliases are read before the build, like permalinks, so large sites built with worker threads resolve every alias. Redirect pages Quartz writes for `slugs.stripDiacritics` keep the `#anchor` of the address they redirect from.
|
||||
- ad10a98: Alias redirect pages keep the `#anchor` of the address they redirect from (`@quartz-community/alias-redirects` 1.0.5), so a link from outside the site to `alias#heading` lands on the heading instead of the top of the page.
|
||||
- 706b6fd: The config schema (editor validation of `quartz.config.yaml`) accepts `configuration.fonts`, `theme.typography.title`, and fonts given with their weights (`{ name, weights, includeItalic }`), which the build already supported. With `extends`, a partial `theme` (for example one colour) is no longer reported as missing `fontOrigin`, `typography` or `darkMode`.
|
||||
- f2015a4: Reinstalling an npm plugin at the version pinned in `quartz.lock.json` (after a fresh clone, or on a CI runner) no longer rewrites its `installedAt`, so `npx quartz plugin install` leaves the lockfile unchanged, as it does for Git plugins.
|
||||
- c92fed9: Popovers show next to their link with Obsidian themes (quartz-themes-core) too: its Obsidian base styles made them `position: absolute`, so on a scrolled page they appeared a scroll's height above the link, often off screen — links to headings and an embed's "link to original" seemed to show no popover. A popover for a link to a heading now also scrolls the heading to the top of the popover when the theme positions the page's content box.
|
||||
- 87ee900: Links resolve as in Obsidian in more cases (`@quartz-community/utils` 1.3.5): `[[./index|index]]` in a subfolder links to that folder's index page instead of the home page; when several notes share a name, a link prefers the one under the linking note's folder, then the shortest path, instead of pointing to a page that doesn't exist (for example `[Status](current.md)` in a vault where several folders have a `current.md`); a `../` link that names no note resolves from the folder it leads to; and a link starting with `/` is a path from the root.
|
||||
|
||||
## 5.4.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 9ebfc67: `extends` in `quartz.config.yaml` is stable for `default` and local paths: its merge rules won't change in a minor release. `https://` URLs stay experimental. Keys starting with `$` are now reserved in every file of an `extends` chain (the top-level `$schema` aside), so merge operators such as appending to a list can be added later without changing existing configs; a config that uses one stops with an error naming the key. Configs without `extends` are not affected.
|
||||
- cc8d104: `quartz.lock.json` is read and written next to the config file Quartz uses, and every `npx quartz plugin` command takes `--config` / `-C` like `build`. A site's repository can hold its content, `quartz.config.yaml` and `quartz.lock.json` while Quartz is checked out elsewhere (as the GitHub Action will). With the config in Quartz's folder nothing changes, and a config elsewhere keeps using an existing lockfile in Quartz's folder until its own folder has one. Plugin commands with a config chosen by `QUARTZ_CONFIG_PATH` now also edit that file; they used to write their changes to `./quartz.config.yaml`.
|
||||
- b86276f: npm plugins that Quartz's `package.json` doesn't list are pinned in `quartz.lock.json` (version and integrity) and installed into `.quartz/plugins/@scope/name`, like Git plugins. `plugin add`, and `plugin install --from-config` (e.g. for the `obsidian` and `ttrpg` templates' Excalidraw plugin), no longer write them into Quartz's `package.json`, so `npx quartz upgrade` doesn't conflict with your plugins, and `npm install` / `npm ci` can't remove them. `plugin install`, `--latest`, `restore`, `remove`, `prune`, `list`, `doctor` and `npx quartz plugin` handle them alongside Git plugins, and a build installs a missing one at its pinned version. npm plugins in `package.json` (the default plugins, and any you `npm install` yourself) are versioned there and load from `node_modules`, as before: when a plugin is in both, `package.json` wins.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ea4b075: Plugin update: og-image 1.2.0. A page's social image (`socialImage`, or Obsidian's `image` / `cover` property) can be an image in the content folder, written as a wikilink (`[[cover.png]]`), a path from the content folder, a path relative to the note, or a bare file name. Before, every value that was not a URL was read as a path in `quartz/static/`.
|
||||
|
||||
## 5.3.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- f285e12: A plugin that depends on a plugin of another pipeline stage (an emitter or component on a transformer) no longer fails the build because of their `order`: order is checked only between plugins of the same stage.
|
||||
- ce108c8: A `locale` that Quartz has no translation for (such as `sv-SE`, `da-DK` or `es-MX`) no longer crashes the build. Quartz uses a translation of the same language (`es-MX` uses `es-ES`), else English, and prints one warning; dates still use the configured locale.
|
||||
- 9889d3f: Plugin updates: folder-page 1.1.5 (a folder's unlisted `index.md` is no longer replaced by a generated folder page), canvas-page 1.1.7 (edges drawn as in Obsidian), search 1.1.5 (Escape with tag suggestions open closes only the suggestions), graph 1.0.10 (the local graph is drawn once per page), stacked-pages 1.0.5 (unused template exports removed) and remark-obsidian 2.2.6.
|
||||
- 37a61cf: Plugin updates with the fixes from a test audit:
|
||||
|
||||
- note-properties: an empty `tags:` or `aliases:` no longer fails the build.
|
||||
- bases-page: sorting, filters, formulas and group headings work as in Obsidian.
|
||||
- encrypted-pages: a numeric `password` encrypts the page, and a custom `outputPath` works.
|
||||
- darkmode, reader-mode, syntax-highlighting and comments: no double handlers after a page is unlocked.
|
||||
- stacked-pages: links work under a base path.
|
||||
- breadcrumbs: `resolveFrontmatterTitle` is honoured.
|
||||
- canvas-page: a `#View` link selects that view.
|
||||
- search: fields left out of `fieldPriority` are searched, and excerpts keep their last word.
|
||||
- explorer: a note next to a folder of the same name stays listed, and folder options apply.
|
||||
- folder-page, og-image, description, table-of-contents, graph, obsidian-flavored-markdown and utils: smaller fixes.
|
||||
- latex: `customMacros` work with MathJax. ox-hugo: figure parameters in backticks.
|
||||
|
||||
- 6729a1e: Relative links and embeds keep their query string after SPA navigation and in popovers (`./viewer.html?file=a.pdf` no longer loses `?file=a.pdf`).
|
||||
- c68a494: Some fixes in this release change how existing pages look, mostly to match Obsidian: Bases sorting (natural text order, empty values last, mixed types), Bases `not:` filters and `== null`, Bases group headings, canvas edges, and folders with an unlisted `index.md`. See [Upgrading from 5.3.0 to 5.3.1](https://quartz.jzhao.xyz/getting-started/upgrading#upgrading-from-530-to-531).
|
||||
- 57b3b5d: `npx quartz plugin install --latest` (and `plugin update`) no longer fails because a disabled plugin can't be updated, for example an old `quartz-themes` entry whose repository moved its plugin. The build doesn't load disabled plugins, so this is now a warning that says how to remove the entry. A failing enabled plugin still fails the command.
|
||||
- 1e1a356: utils 1.3.4: inline `#tag` links from notes two or more folders deep stay under the site's base path. They went to `/tags/…` instead of `/<base>/tags/…`, a 404 on sites served under a sub-path such as GitHub Pages project sites.
|
||||
|
||||
## 5.3.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -65,6 +65,13 @@ By default Quartz loads `quartz.config.yaml` from the current working directory.
|
||||
npx quartz build --config ../my-vault/quartz.config.yaml
|
||||
```
|
||||
|
||||
`quartz.lock.json` is read from the same folder as the config, so a site's repository can hold its content, `quartz.config.yaml` and `quartz.lock.json` together while Quartz is checked out elsewhere. Plugins are still installed into Quartz's `.quartz/plugins/`. Use the same `--config` with the [[cli/plugin|plugin]] commands, which pin plugins in that lockfile. (A config in a folder without a lockfile keeps using an existing `quartz.lock.json` in Quartz's folder.) The [[github-action|Quartz GitHub Action]] builds sites this way.
|
||||
|
||||
```shell
|
||||
npx quartz plugin install --config ../my-vault/quartz.config.yaml
|
||||
npx quartz build --config ../my-vault/quartz.config.yaml -d ../my-vault/content
|
||||
```
|
||||
|
||||
> [!note]
|
||||
> The shorthand for `--config` is an uppercase `-C`. A lowercase `-c` is the shorthand for `--concurrency`, so the two are distinct.
|
||||
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ These flags are accepted by every Quartz command:
|
||||
| `--verbose` | `-v` | Enable detailed logging for debugging | `false` |
|
||||
| `--concurrency` | `-c` | Max parallel workers for operations that run in parallel (e.g. `build`, `plugin install`, `plugin add`) | CPU core count |
|
||||
|
||||
Commands that don't perform parallel work accept `-c` as a no-op, so it's always safe to pass. See [[build#Performance Tuning|build]] and [[cli/plugin#Installing on low-end hardware|plugin]] for practical examples.
|
||||
Commands that don't perform parallel work accept `-c` as a no-op, so it's always safe to pass. See [[cli/build#Performance Tuning|build]] and [[cli/plugin#Installing on low-end hardware|plugin]] for practical examples.
|
||||
|
||||
## Help and Versioning
|
||||
|
||||
|
||||
+11
-7
@@ -6,18 +6,20 @@ The `plugin` command is the heart of the Quartz v5 plugin management system. it
|
||||
|
||||
Quartz plugins come from two kinds of sources:
|
||||
|
||||
- **npm packages** (`@quartz-community/explorer`) — the default plugins. They are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`.
|
||||
- **npm packages** (`@quartz-community/explorer`). Those in Quartz's `package.json` — the default plugins, and any you install with `npm install` yourself — are installed into `node_modules/` by `npm install` / `npm ci` and versioned by `package.json` and `package-lock.json`. Other npm plugins are pinned in `quartz.lock.json` (version and integrity) and installed into `.quartz/plugins/@scope/name`, like Git plugins: `plugin add` doesn't change Quartz's `package.json`, so `npx quartz upgrade` doesn't conflict with your plugins, and `npm install` / `npm ci` can't remove them. When a plugin is in both, `package.json` wins.
|
||||
- **Git repositories and local directories** (`github:owner/repo`, `./my-plugin`) — cloned or symlinked into `.quartz/plugins/`. Their exact commits are pinned in `quartz.lock.json`.
|
||||
|
||||
Wherever a command takes a plugin name you can use the full name (`@quartz-community/explorer`), the source as written in `quartz.config.yaml`, or the short name (`explorer`). Misspelled names get a "did you mean" suggestion.
|
||||
|
||||
Every subcommand takes `--config` / `-C`, like [[cli/build#Custom config file|build]]: it reads and edits that config file, and the `quartz.lock.json` next to it, instead of `./quartz.config.yaml` and `./quartz.lock.json`.
|
||||
|
||||
Every subcommand exits with a non-zero status when something fails (a clone, a build, an unknown plugin name), so `npx quartz plugin install && npx quartz build` stops in CI instead of building a site with missing plugins.
|
||||
|
||||
## Subcommands
|
||||
|
||||
### list
|
||||
|
||||
List all configured plugins: Git/local plugins with their pinned commit, npm plugins with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
|
||||
List all configured plugins: plugins pinned in `quartz.lock.json` (Git/local plugins with their commit, npm plugins with their version), npm plugins from `package.json` with their installed version, and any plugins that are in `quartz.config.yaml` but not installed yet.
|
||||
|
||||
```shell
|
||||
npx quartz plugin list
|
||||
@@ -25,7 +27,7 @@ npx quartz plugin list
|
||||
|
||||
### add
|
||||
|
||||
Add a new plugin from npm or a Git repository. The plugin is installed (Git plugins are pinned in `quartz.lock.json`, npm packages recorded in `package.json`), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
|
||||
Add a new plugin from npm or a Git repository. The plugin is installed and pinned in `quartz.lock.json` (Git plugins by commit, npm packages by version; an npm package already in `package.json` stays versioned there), and added to `quartz.config.yaml` with its default options — enabled unless the plugin is disabled by default.
|
||||
|
||||
```shell
|
||||
npx quartz plugin add @quartz-community/graph # an npm package, as the default config uses
|
||||
@@ -67,7 +69,7 @@ npx quartz plugin remove plugin-name
|
||||
npx quartz plugin remove explorer # short name of @quartz-community/explorer
|
||||
```
|
||||
|
||||
For npm plugins the package stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
|
||||
A pinned npm plugin is removed from `.quartz/plugins/` and `quartz.lock.json`; an npm plugin from `package.json` stays in `node_modules/` (most of them ship with Quartz). If another configured plugin declares a dependency on the one you removed, a warning tells you so.
|
||||
|
||||
### install
|
||||
|
||||
@@ -77,7 +79,9 @@ Install plugins for your Quartz project. By default, this installs all plugins l
|
||||
npx quartz plugin install
|
||||
```
|
||||
|
||||
If there is no `quartz.lock.json` yet, `install` falls back to installing the Git/local plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists Git plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
|
||||
If there is no `quartz.lock.json` yet, `install` falls back to installing the plugins from `quartz.config.yaml` and writes the lockfile — commit it to pin those versions. If only npm plugins from `package.json` are configured there is nothing to do and the command says so. When `quartz.config.yaml` lists plugins that are missing from the lockfile, `install` prints them with a hint to run `install --from-config`.
|
||||
|
||||
`npx quartz build` also installs a pinned npm plugin that is missing from `.quartz/plugins/`, at the version the lockfile pins.
|
||||
|
||||
> [!note]
|
||||
> `npx quartz build` also installs any configured Git plugin that is missing from `.quartz/plugins/`, and checks out the commit pinned in `quartz.lock.json` when there is one. Running `plugin install` first is still recommended in CI, because it fails loudly when a plugin cannot be installed.
|
||||
@@ -85,7 +89,7 @@ If there is no `quartz.lock.json` yet, `install` falls back to installing the Gi
|
||||
#### Flags
|
||||
|
||||
- `--from-config`: Synchronize plugins with `quartz.config.yaml` instead of the lockfile. This will install missing plugins and prune orphaned ones.
|
||||
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile.
|
||||
- `--latest`: Fetch the latest version of plugins from their remote sources instead of using the version in the lockfile (for a pinned npm plugin, the version npm's `latest` tag points at).
|
||||
- `--clean`: Only restore plugins whose directory is missing; existing directories are left untouched.
|
||||
- `--dry-run`: Preview the changes without actually installing or removing any files.
|
||||
- `--concurrency`, `-c`: Maximum number of plugins to clone, fetch, and build in parallel. Defaults to the number of CPU cores. Lower this (e.g. `-c 1` or `-c 2`) on memory- or CPU-constrained machines where the default parallelism causes failures, OOMs, or hangs. See [[#Installing on low-end hardware]] below.
|
||||
@@ -348,4 +352,4 @@ Running the plugin command without any subcommand shows a status dashboard of al
|
||||
npx quartz plugin
|
||||
```
|
||||
|
||||
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks Git plugins for available updates in parallel. npm plugins are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
|
||||
This displays each plugin with its source, commit (or npm version), enabled/disabled status, and checks pinned plugins for available updates in parallel (Git plugins against their repository, npm plugins against npm). npm plugins in `package.json` are updated together with Quartz (`npx quartz upgrade`). A misspelled subcommand (e.g. `npx quartz plugin lst`) is reported as an error with a suggestion instead of falling back to this dashboard. For the full interactive management interface, use [[tui|npx quartz tui]] instead.
|
||||
+26
-32
@@ -44,17 +44,20 @@ plugins:
|
||||
|
||||
- `extends` is `default`, a path to another config file relative to this one (which may itself extend another), an `https://` URL, or a list of those. An empty file (or one with only comments) is an empty config, and `extends: []` extends nothing.
|
||||
- A list stacks presets: each file in it adds its own changes. Quartz puts every file of the `extends` chain in one line and applies each once, its bases before it: the list's entries in order, each after the bases it extends, and your file last. A base that several entries share (usually `default`) is applied once, at its first appearance. So with `extends: [./a.yaml, ./b.yaml]`, where both extend `default`, the order is `default` → `a.yaml` → `b.yaml` → your file: what `a.yaml` changes stays unless `b.yaml` changes the same thing (later entries win), and your file wins over both. An entry that doesn't extend the shared base is applied before it if it comes first, so the base's settings win over it; make such a preset extend `default` too, or list it after the others.
|
||||
- A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
|
||||
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies.
|
||||
- **Experimental:** `https://` URLs. How they are fetched, cached and trusted may still change. A URL is fetched when the config is loaded (10 s timeout, at most 1 MB) and kept in `.quartz-cache/extends/`. If a later fetch fails (offline, timeout, HTTP error), Quartz uses the cached copy and warns; without one, the build stops. `QUARTZ_EXTENDS_OFFLINE=1` uses only the cached copy. Relative `extends` inside a fetched file are resolved against its URL; `default` always means your local `quartz.config.default.yaml`. Only `https://` URLs are allowed, and only extend configs you trust: they choose which plugins your build runs.
|
||||
- `configuration` and `layout` merge key by key, including nested objects (`theme.colors.lightMode.secondary` changes only that colour). Any other value replaces the default: strings, numbers and lists such as `ignorePatterns` or `byPageType.<type>.exclude`. Setting a key to `null` removes it, so the built-in default applies. (An editor that validates the file against Quartz's schema may flag such a `null`; the build accepts it.)
|
||||
- A plugin entry changes the default entry for the same plugin, matched by name (`github:quartz-community/explorer` matches `@quartz-community/explorer`, and a fork with the same name replaces it). A source with a `name` matches by that name; a source with a `subdir` and no `name` matches by repository and folder, so two plugins of one repository stay separate. `enabled`, `order` and `source` replace the default values. `options` and `layout` merge like `configuration`, and `null` drops them so the plugin's own defaults apply. A plugin that is not in the base is added, and it needs `enabled: true` just as in a full config.
|
||||
- Keys starting with `$` are reserved in every file of an `extends` chain, at any depth (the top-level `$schema` aside): they are kept free for merge operators, such as adding to a list instead of replacing it. A config that uses one stops with an error naming the key. Values may contain `$` freely.
|
||||
- Plugins run in `order` as before. Your file can change a default plugin's `order`. Where two plugins have the same order, the base config's list order decides, and added plugins come last.
|
||||
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over.
|
||||
- Your updates to `quartz.config.default.yaml` (for example after `npx quartz upgrade`) reach your site without copying them over. The [[github-action|GitHub Action]] builds with the defaults of the Quartz release it uses, so a config that extends `default` follows them too.
|
||||
|
||||
- `npx quartz build --serve` also rebuilds when a local file your config extends changes.
|
||||
- `npx quartz plugin` commands and `npx quartz info` read the merged configuration, as the build does: `plugin list`, `status`, `doctor`, `install` and `prune` see the plugins your bases configure. Commands that change plugins only ever write your own file, never the merged result: `enable`, `disable` and `config --set` add or change your entry for the plugin (`- source: …` with just that change), `config --unset` removes your value and, when a base sets the option, sets it to `null` so the plugin's default applies, and `add` appends a full entry. `remove` refuses a plugin that a base configures (it can't be removed from your file); disable it instead.
|
||||
|
||||
> [!warning] Experimental
|
||||
> `extends` is experimental: the merge rules may still change.
|
||||
> [!note] Stability
|
||||
> `extends` with `default` and local paths is stable: the merge rules above don't change in a minor release. `https://` URLs are experimental.
|
||||
>
|
||||
> A Quartz upgrade can change the defaults your site extends. A changed default applies to your site unless your file sets that value itself.
|
||||
|
||||
## General Configuration
|
||||
|
||||
@@ -108,7 +111,7 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
|
||||
Use a path relative to the site root like above (no leading `/`) so it also works when the site is served from a subpath. To have Quartz download Google Fonts at build time and serve them from your site instead, set `configuration.fonts.fontOrigin: selfHosted` (see [[plugins/Fonts|Fonts]]).
|
||||
- `cdnCaching`: if `true` (default), use Google CDN to cache the fonts. This will generally be faster. Disable (`false`) this if you want Quartz to download the fonts to be self-contained.
|
||||
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here.
|
||||
- `typography`: what fonts to use. Any font available on [Google Fonts](https://fonts.google.com/) works here, as a name or with its weights (see [[#Fonts]]).
|
||||
- `title`: font for the title of the site (optional, same as `header` by default)
|
||||
- `header`: font to use for headers
|
||||
- `code`: font for inline and block quotes
|
||||
@@ -123,8 +126,8 @@ This part of the configuration concerns anything that can affect the whole site.
|
||||
- `tertiary`: hover states and visited [[graph view|graph]] nodes
|
||||
- `highlight`: internal link background, highlighted text, [[syntax highlighting|highlighted lines of code]]
|
||||
- `textHighlight`: markdown highlighted text background
|
||||
- `frontmatter`, `links`, `drafts`, `contentIndex`: options for Quartz's [[built-in processing]] — frontmatter parsing ([[Frontmatter]]), link resolution ([[CrawlLinks]]), draft handling ([[RemoveDrafts]]) and the content index, sitemap and RSS feed ([[ContentIndex]]). They are on by default. Each takes an object of options (plus `enabled` and `order`) or a boolean shorthand: set e.g. `links: { markdownLinkResolution: relative }` to change an option or `contentIndex: false` to turn one off.
|
||||
- `links.markdownLinkResolution` defaults to `shortest` (Obsidian's default). An old `crawl-links` plugin entry that Quartz migrates keeps that plugin's default, `absolute`, unless it sets another value.
|
||||
- `frontmatter`, `links`, `drafts`, `contentIndex`, `fonts`: options for Quartz's [[built-in processing]] — frontmatter parsing ([[Frontmatter]]), link resolution ([[CrawlLinks]]), draft handling ([[RemoveDrafts]]), the content index, sitemap and RSS feed ([[ContentIndex]]) and font loading ([[plugins/Fonts|Fonts]]). They are on by default. Each takes an object of options (plus `enabled` and `order`) or a boolean shorthand: set e.g. `links: { markdownLinkResolution: relative }` to change an option or `contentIndex: false` to turn one off.
|
||||
- `links.markdownLinkResolution` defaults to `shortest`, which resolves links as Obsidian does (see [[CrawlLinks]]). An old `crawl-links` plugin entry that Quartz migrates keeps that plugin's default, `absolute`, unless it sets another value.
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
configuration:
|
||||
@@ -232,7 +235,7 @@ plugins:
|
||||
dark: github-dark
|
||||
```
|
||||
|
||||
Frontmatter parsing, link resolution, drafts and the content index are not plugins: they are [[built-in processing|built into Quartz]] and configured under `configuration.frontmatter`, `.links`, `.drafts` and `.contentIndex`. Everything else is a plugin, referenced by its source: npm plugins (all the default ones) are installed in `node_modules`, Git and local plugins in `.quartz/plugins/`.
|
||||
Frontmatter parsing, link resolution, drafts and the content index are not plugins: they are [[built-in processing|built into Quartz]] and configured under `configuration.frontmatter`, `.links`, `.drafts` and `.contentIndex`. Everything else is a plugin, referenced by its source. npm plugins in Quartz's `package.json` (all the default ones) are installed in `node_modules`; other npm plugins, and Git and local plugins, are installed in `.quartz/plugins/` and pinned in `quartz.lock.json`.
|
||||
|
||||
### Community Plugins
|
||||
|
||||
@@ -243,7 +246,9 @@ npx quartz plugin add @quartz-community/explorer # an npm package
|
||||
npx quartz plugin add github:username/repo # a Git repository
|
||||
```
|
||||
|
||||
This adds the plugin to `quartz.config.yaml` and installs it to `.quartz/plugins/`.
|
||||
This adds the plugin to `quartz.config.yaml`, installs it to `.quartz/plugins/`, and pins it in `quartz.lock.json`: a Git plugin by commit, an npm plugin by version. Commit the lockfile, so that every build, on any machine or in CI, uses the same plugin versions.
|
||||
|
||||
`quartz.lock.json` sits next to `quartz.config.yaml`. For a config file elsewhere, pass the same `--config` to the plugin commands as to `build` (see [[cli/build#Custom config file]]).
|
||||
|
||||
To install all plugins referenced in your config that aren't yet installed (useful when cloning a project or setting up CI):
|
||||
|
||||
@@ -388,29 +393,18 @@ configuration:
|
||||
code: IBM Plex Mono
|
||||
```
|
||||
|
||||
> [!note]
|
||||
> Quartz uses `title`, but the config's JSON schema doesn't list it yet, so an editor with YAML validation may flag it. The warning can be ignored.
|
||||
For more control over font weights and italics, give a font as an object with `name`, `weights` and `includeItalic`:
|
||||
|
||||
For more control over font weights and italics, use the TS override in `quartz.ts`:
|
||||
|
||||
```ts title="quartz.ts"
|
||||
import { loadQuartzConfig, loadQuartzLayout } from "./quartz/plugins/loader/config-loader"
|
||||
|
||||
const config = await loadQuartzConfig({
|
||||
theme: {
|
||||
typography: {
|
||||
header: {
|
||||
name: "Schibsted Grotesk",
|
||||
weights: [400, 700],
|
||||
includeItalic: true,
|
||||
},
|
||||
body: "Source Sans Pro",
|
||||
code: "IBM Plex Mono",
|
||||
},
|
||||
},
|
||||
})
|
||||
export default config
|
||||
export const layout = await loadQuartzLayout()
|
||||
```yaml title="quartz.config.yaml"
|
||||
configuration:
|
||||
theme:
|
||||
typography:
|
||||
header:
|
||||
name: Schibsted Grotesk
|
||||
weights: [400, 700]
|
||||
includeItalic: true
|
||||
body: Source Sans Pro
|
||||
code: IBM Plex Mono
|
||||
```
|
||||
|
||||
> [!tip]
|
||||
|
||||
@@ -6,12 +6,23 @@ tags:
|
||||
|
||||
Quartz comes shipped with a Docker image that will allow you to preview your Quartz locally without installing Node.
|
||||
|
||||
You can run the below one-liner to run Quartz in Docker.
|
||||
From your copy of Quartz, run the below one-liner to build the image and run Quartz in Docker.
|
||||
|
||||
```sh
|
||||
docker run --rm -itp 8080:8080 -p 3001:3001 -v ./content:/usr/src/app/content $(docker build -q .)
|
||||
```
|
||||
|
||||
Each Quartz release is also published as an image, `ghcr.io/jackyzha0/quartz`, tagged with its version (`5.4.1`), its minor version (`5.4`) and `latest`. To preview a folder of notes and your configuration with it:
|
||||
|
||||
```sh
|
||||
docker run --rm -itp 8080:8080 -p 3001:3001 \
|
||||
-v ./content:/usr/src/app/content \
|
||||
-v ./quartz.config.yaml:/usr/src/app/quartz.config.yaml \
|
||||
ghcr.io/jackyzha0/quartz:5.4
|
||||
```
|
||||
|
||||
Leave out the second `-v` to use Quartz's default configuration.
|
||||
|
||||
> [!warning] Not to be used for production
|
||||
> Serve mode is intended for local previews only.
|
||||
> For production workloads, see the page on [[hosting]].
|
||||
@@ -14,7 +14,7 @@ Additionally, Quartz will also generate pages for subfolders. Say you have a not
|
||||
|
||||
You can link to the folder listing by referencing its name, plus a trailing slash, like this: `[[advanced/]]` (results in [[advanced/]]).
|
||||
|
||||
By default, Quartz will title the page with the folder name (set the [[FolderPage]] option `prefixFolders: true` for `Folder: <folder name>`) and no description. You can override this by creating an `index.md` file in the folder with the `title` [[authoring content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the folder description.
|
||||
By default, Quartz will title the page with the folder name (set the [[FolderPage]] option `prefixFolders: true` for `Folder: <folder name>`) and no description. You can override this by creating an `index.md` file in the folder with the `title` [[getting-started/authoring-content#Syntax|frontmatter]] field. Any content you write in this file will also be used in the folder description.
|
||||
|
||||
For example, for the folder `content/posts`, you can add another file `content/posts/index.md` to add a specific description for it.
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ Quartz supports Wikilinks by default and these links are resolved by Quartz's bu
|
||||
|
||||
Parsing wikilinks is part of [[Obsidian compatibility]] ([[ObsidianFlavoredMarkdown]]). How links are resolved (`markdownLinkResolution`, pretty link text, broken-link styling, …) is configured under `configuration.links` (see [[CrawlLinks]]).
|
||||
|
||||
A link names a note by its file name (`[[My Note]]`) or a path (`[[folder/My Note]]`). When several notes match, the link goes, as in Obsidian, to the note whose path is exactly the link (`[[note]]` → `note.md` at the root), else to one under the linking note's folder, else to the one with the shortest path; see `markdownLinkResolution` in [[CrawlLinks]].
|
||||
|
||||
Wikilink matching is case-insensitive to mirror Obsidian: `[[My Note]]`, `[[my note]]`, and `[[MY NOTE]]` all resolve to the same file. The generated URL is lowercased (e.g. `my-note`).
|
||||
|
||||
Links behave as in Obsidian in a few more ways:
|
||||
|
||||
@@ -30,6 +30,9 @@ Follow these in order:
|
||||
3. **[[installation#Setting Up Your GitHub Repository|Push to GitHub]]** — Create a repository and push your site with `npx quartz sync`
|
||||
4. **[[hosting|Deploy]]** — Host your site for free on GitHub Pages, Cloudflare, Netlify, or Vercel
|
||||
|
||||
> [!tip]
|
||||
> To publish notes from a GitHub repository without a copy of Quartz, skip these steps and use the [[github-action|Quartz GitHub Action]].
|
||||
|
||||
## Upgrading & Migrating
|
||||
|
||||
- **[[whats-new|What's New in Quartz 5]]** — Overview of new features and changes
|
||||
|
||||
@@ -6,6 +6,9 @@ aliases:
|
||||
|
||||
This page walks you through the full Quartz setup: from getting the source code to previewing your site locally, then pushing it to GitHub.
|
||||
|
||||
> [!tip] Only want to publish your notes?
|
||||
> To publish an Obsidian vault or a `docs/` folder on GitHub Pages without changing Quartz itself, you don't need your own copy of Quartz: the [[github-action|Quartz GitHub Action]] builds the site from a repository that holds only your notes. Follow this page to preview your site locally, customize Quartz's code, or host it elsewhere.
|
||||
|
||||
## 1. Get Quartz
|
||||
|
||||
There are two ways to get started. Pick whichever you prefer:
|
||||
|
||||
@@ -158,7 +158,7 @@ Here's the recommended pattern, based on the project's own GitHub Actions:
|
||||
|
||||
```yaml
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
@@ -166,7 +166,7 @@ Here's the recommended pattern, based on the project's own GitHub Actions:
|
||||
${{ runner.os }}-node-
|
||||
|
||||
- name: Cache Quartz plugins
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: .quartz/plugins
|
||||
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
|
||||
@@ -190,7 +190,7 @@ For non-GitHub CI providers (Cloudflare, Vercel, Netlify), the build command sho
|
||||
npx quartz plugin install && npx quartz build
|
||||
```
|
||||
|
||||
See [[hosting]] for provider-specific setup details.
|
||||
See [[hosting]] for provider-specific setup details. If your repository only needs your notes and settings, the [[github-action|Quartz GitHub Action]] can build it instead, without a copy of Quartz.
|
||||
|
||||
## Setting Your Default Branch to v5
|
||||
|
||||
|
||||
@@ -28,6 +28,77 @@ npx quartz plugin install --latest
|
||||
|
||||
See the [[upgrade|CLI reference for upgrade]] for more details on available flags.
|
||||
|
||||
## Upgrading from 5.4.0 to 5.4.1
|
||||
|
||||
5.4.1 is a patch release. Upgrade as usual:
|
||||
|
||||
```bash
|
||||
npx quartz upgrade
|
||||
```
|
||||
|
||||
### Changes you may notice
|
||||
|
||||
- **Links resolve as in Obsidian in more cases** (with the default `markdownLinkResolution: shortest`; see [[CrawlLinks]]). A link can now reach a different page than before:
|
||||
- `[[./index|index]]` in a subfolder links to that folder's index page. It went to the home page.
|
||||
- When several notes share a name, a link reaches the one under the linking note's folder, else the one with the shortest path. Before, a link such as `[Status](current.md)` in a vault where several folders have a `current.md` could point to a page that doesn't exist.
|
||||
- A `../` link that names no note there resolves from the folder it leads to, and a link starting with `/` is a path from the content folder's root.
|
||||
- **Popovers with an Obsidian theme** ([[ThemesCore]]) show next to their link. On a scrolled page they appeared too high, often off screen, so links to headings and an embed's "link to original" seemed to show no popover.
|
||||
- **`npx quartz plugin install`** no longer changes `quartz.lock.json` when it reinstalls a pinned npm plugin (after a fresh clone or in CI).
|
||||
|
||||
## Upgrading from 5.3 to 5.4
|
||||
|
||||
```bash
|
||||
npx quartz upgrade
|
||||
npx quartz plugin install --latest
|
||||
```
|
||||
|
||||
### Changes you may notice
|
||||
|
||||
- **npm plugins are pinned in `quartz.lock.json`**: `npx quartz plugin add @scope/plugin` and `plugin install --from-config` no longer add npm plugins to Quartz's `package.json`. They are pinned in `quartz.lock.json` and installed into `.quartz/plugins/`, like Git plugins, so `npx quartz upgrade` can't conflict with them in `package.json` and `npm ci` can't remove them. See [[cli/plugin]].
|
||||
|
||||
npm plugins that are already in your `package.json` (added by `plugin add` before 5.4, or the Excalidraw plugin of the `obsidian` and `ttrpg` templates) keep working from there: when a plugin is in both, `package.json` wins. To move one to the lockfile, uninstall it and let Quartz pin it, then commit `package.json`, `package-lock.json` and `quartz.lock.json`:
|
||||
|
||||
```bash
|
||||
npm uninstall @quartz-community/obsidian-plugin-excalidraw
|
||||
npx quartz plugin install --from-config
|
||||
```
|
||||
|
||||
- **`extends` is stable** for `default` and local paths: its merge rules won't change in a minor release. `https://` URLs stay experimental. See [[configuration#Extending the default configuration]].
|
||||
- **Keys starting with `$` are reserved** in every file of an `extends` chain (the top-level `$schema` aside), for future merge operators. A config that uses one stops with an error naming the key; rename it. Configs without `extends` are not affected.
|
||||
- **`quartz.lock.json` sits next to the config file**. With `quartz.config.yaml` in Quartz's folder nothing changes. With `--config` pointing elsewhere, the lockfile is read and written in that folder. An existing `quartz.lock.json` in Quartz's folder is still used until that folder has one of its own. Plugin commands now take `--config` / `-C` too, and with `QUARTZ_CONFIG_PATH` they edit that file instead of `./quartz.config.yaml`. See [[cli/build#Custom config file]].
|
||||
|
||||
### New
|
||||
|
||||
- The [[github-action|Quartz GitHub Action]] builds a site from a repository that holds only your notes.
|
||||
|
||||
See [[whats-new#New in 5.4|What's new in 5.4]].
|
||||
|
||||
## Upgrading from 5.3.0 to 5.3.1
|
||||
|
||||
5.3.1 is a patch release: fixes from a test audit of Quartz and its plugins, many checked against Obsidian. Upgrade as usual:
|
||||
|
||||
```bash
|
||||
npx quartz upgrade
|
||||
npx quartz plugin install --latest
|
||||
```
|
||||
|
||||
### Changes you may notice
|
||||
|
||||
Most of these make a page look the way Obsidian shows it, so an existing site can look different after the upgrade.
|
||||
|
||||
- **[[Bases]] sorting**: text sorts naturally ("Chapter 2" before "Chapter 10") and ignores case, also for the default order by file name. Empty values come last in both directions, including descending sorts. A column that mixes types sorts numbers, dates and durations by value and everything else as text. Group order follows the same rules.
|
||||
- **[[Bases]] filters and formulas**, as in Obsidian:
|
||||
- `not:` leaves out a note that matches _any_ of its conditions (it left out only notes matching all of them).
|
||||
- `status == null` matches notes without `status`, and `status != null` no longer keeps them.
|
||||
- `"5" == 5` and `1 == true` are true, two strings compare as text (`"10" > "9"` is false), and an empty list counts as false.
|
||||
- A formula can use a formula defined after it. `x / 0` shows ∞. `sum()`, `mean()`, `min()` and `max()` skip text and booleans, and are empty without numbers. `number("abc")` is an error.
|
||||
- **[[Bases]] group headings** show their value as a cell does: dates in the local format (not an ISO timestamp, sometimes of the previous day), durations as "4 days", links as the note's name, booleans as a checkbox.
|
||||
- **[[CanvasPage|Canvas]] edges** leave and enter each card through the side they name, with Obsidian's curve, and the arrow points into that side. An edge without sides joins the sides that face each other (it joined the cards' centres).
|
||||
- **Folder pages**: a folder whose own `index.md` is unlisted shows that note, with the folder listing below it. A generated folder page used to replace it.
|
||||
- **Tag links under a base path**: inline `#tag` links from notes two or more folders deep stay on the site. On a site served under a sub-path, such as a GitHub Pages project site, they went to `/tags/…` and returned 404.
|
||||
- **Locales without a translation** (such as `sv-SE`) no longer crash the build: Quartz uses a translation of the same language, else English, and prints a warning. Dates still use your locale.
|
||||
- **`npx quartz plugin install --latest`** no longer fails because a _disabled_ plugin can't be updated (for example an old `quartz-themes` entry). It prints a warning with the command to remove the entry.
|
||||
|
||||
## Upgrading from 5.2 to 5.3
|
||||
|
||||
Quartz 5.3 needs **Node.js 22.22 or later**. Then upgrade as usual:
|
||||
@@ -65,7 +136,7 @@ npx quartz plugin install --latest
|
||||
|
||||
### New options
|
||||
|
||||
- `extends` (experimental) and `before`/`after` on plugin entries. See [[configuration#Extending the default configuration]].
|
||||
- `extends` (experimental in 5.3, stable since 5.4) and `before`/`after` on plugin entries. See [[configuration#Extending the default configuration]].
|
||||
- `configuration.slugs.stripDiacritics`. See [[configuration#General Configuration]].
|
||||
- The layout conditions `is-index`, `is-folder-index` and `not-<condition>`. See [[layout#Conditional Rendering]].
|
||||
- [[plugins/Explorer|Explorer]]: `sort`, `rootFolder`, and `order` in YAML. [[GitHubFlavoredMarkdown]]: `singleTilde`, `replacements`. [[ObsidianFlavoredMarkdown]]: `math`, `markdownEmbeds`, `blockWrappers`, `foldHeadings`, `foldLists`. [[CanvasPage]]: `wheelBehavior`, `textNodeMarkdown`.
|
||||
|
||||
@@ -7,16 +7,26 @@ aliases:
|
||||
|
||||
Quartz 5 is a ground-up rearchitecture of Quartz focused on extensibility, performance, and Obsidian compatibility. If you're coming from v4, see [[migrating|Migrating to Quartz 5]] for the upgrade path.
|
||||
|
||||
## New in 5.4
|
||||
|
||||
Upgrading from 5.3? See [[getting-started/upgrading#Upgrading from 5.3 to 5.4|Upgrading from 5.3 to 5.4]].
|
||||
|
||||
- **[[github-action|GitHub Action]]** — `quartz-community/action` builds and deploys a site from a repository that holds only your notes: no copy of Quartz, and an optional `quartz.config.yaml` and `quartz.lock.json`. The configuration can also be set in the workflow.
|
||||
- **Stable `extends`** — `extends: default` and local paths are stable: keep only your changes to the default configuration, and Quartz's updated defaults reach your site. See [[configuration#Extending the default configuration]].
|
||||
- **npm plugins in the lockfile** — npm plugins you add are pinned in `quartz.lock.json` (version and integrity) like Git plugins, instead of being written into Quartz's `package.json`, so upgrades don't conflict with them. See [[cli/plugin]].
|
||||
- **Config and lockfile together** — `quartz.lock.json` is read and written next to the config, and every `npx quartz plugin` command takes `--config` / `-C`, so a site's repository can hold its content, config and lockfile while Quartz is checked out elsewhere. See [[cli/build#Custom config file]].
|
||||
- **5.4.1** — links resolve as in Obsidian in more cases (`./` links, several notes with the same name), and popovers are placed correctly with Obsidian themes. See [[getting-started/upgrading#Upgrading from 5.4.0 to 5.4.1|Upgrading from 5.4.0 to 5.4.1]].
|
||||
|
||||
## New in 5.3
|
||||
|
||||
Upgrading from 5.2? See [[upgrading#Upgrading from 5.2 to 5.3|Upgrading from 5.2 to 5.3]] for the changes you may notice.
|
||||
Upgrading from 5.2? See [[getting-started/upgrading#Upgrading from 5.2 to 5.3|Upgrading from 5.2 to 5.3]] for the changes you may notice.
|
||||
|
||||
- **Accessibility** — the templates' colours meet WCAG AA contrast, and so does text in the table of contents, footer, folder and tag listings, search button and Bases group headings. The centre column is a `<main>` and the sidebars are `<aside>` elements, page listings no longer skip heading levels, and ARIA attributes and ids are valid in the table of contents, explorer, backlinks, heading anchors and Bases views.
|
||||
- **Faster pages** — component styles are one stylesheet (about 20 fewer render-blocking requests per page), the [[graph view]] loads d3 and PixiJS only when it is shown and opens five times faster on large sites, and KaTeX's stylesheet no longer blocks pages without math.
|
||||
- **Back and Forward** — with [[SPA Routing]], Back and Forward return to where you were on each page, and moving between headings of the same page only scrolls.
|
||||
- **Markup as in Obsidian** — [[ObsidianFlavoredMarkdown]] wraps each top-level block in Obsidian's `div.el-*` wrappers, renders [[Mermaid diagrams]] with Pele by default, and can fold headings and lists (`foldHeadings`, `foldLists`; on in the `obsidian` template). Transclusions use Obsidian's embed markup, a missing attachment reads "could not be found", and notes embedded with a Markdown link (``) are transcluded. Obsidian themes ([[ThemesCore]] 3.2) style all of these.
|
||||
- **Unresolved links** — links to pages that don't exist, or that a filter removed (drafts, [[ExplicitPublish]]), get the `broken` class, as Obsidian marks unresolved links (`links.disableBrokenWikilinks` is on by default). See [[CrawlLinks]].
|
||||
- **Extending a configuration** (experimental) — `extends: default` in `quartz.config.yaml` keeps only your changes to the default configuration; it also takes a path or an `https://` URL. Several presets can be listed and stack. Plugin entries can declare `before:` / `after:` other plugins. See [[configuration#Extending the default configuration]].
|
||||
- **Extending a configuration** (experimental; stable since 5.4) — `extends: default` in `quartz.config.yaml` keeps only your changes to the default configuration; it also takes a path or an `https://` URL. Several presets can be listed and stack. Plugin entries can declare `before:` / `after:` other plugins. See [[configuration#Extending the default configuration]].
|
||||
- **Slugs without accents** — `configuration.slugs.stripDiacritics` publishes `české/čeština.md` at `/ceske/cestina` and `Łódź.md` at `/lodz`, so URLs in Latin-script languages need no percent-encoding; other scripts are left as written. See [[configuration#General Configuration]].
|
||||
- **Layout conditions** — `is-index` (home page), `is-folder-index`, and `not-<condition>` for any condition (`not-has-tags`). See [[layout#Conditional Rendering]].
|
||||
- **Explorer** 1.2 — sort from YAML with rules applied in sequence (`sort: [folder, { by: date, direction: desc }]`), several explorers on a page (`rootFolder`), and `order` in YAML. See [[plugins/Explorer|Explorer]].
|
||||
@@ -27,7 +37,7 @@ Upgrading from 5.2? See [[upgrading#Upgrading from 5.2 to 5.3|Upgrading from 5.2
|
||||
|
||||
## New in 5.2
|
||||
|
||||
Upgrading from 5.1? See [[upgrading#Upgrading from 5.1 to 5.2|Upgrading from 5.1 to 5.2]].
|
||||
Upgrading from 5.1? See [[getting-started/upgrading#Upgrading from 5.1 to 5.2|Upgrading from 5.1 to 5.2]].
|
||||
|
||||
- **Obsidian themes** — [[ThemesCore]] 3.1 converts any Obsidian community theme at build time: name it as Obsidian lists it (`Minimal`, `AnuPpuccin`), or give a GitHub repository, a URL or a local `theme.css`. Style Settings exports and CSS snippets apply as in Obsidian.
|
||||
- **Fonts built in** — font loading is part of Quartz as `configuration.fonts` (formerly the Fonts plugin), including the interface font and per-heading fonts. See [[configuration#Fonts]].
|
||||
@@ -39,7 +49,7 @@ Upgrading from 5.1? See [[upgrading#Upgrading from 5.1 to 5.2|Upgrading from 5.1
|
||||
|
||||
## New in 5.1
|
||||
|
||||
Upgrading from 5.0? See [[upgrading#Upgrading from 5.0 to 5.1|Upgrading from 5.0 to 5.1]] for the steps and the changes you may notice.
|
||||
Upgrading from 5.0? See [[getting-started/upgrading#Upgrading from 5.0 to 5.1|Upgrading from 5.0 to 5.1]] for the steps and the changes you may notice.
|
||||
|
||||
- **[[prefetching|Prefetching]]** — pages are fetched before their links are followed, so they open at once (`configuration.prefetch`, default `viewport`). Works with and without SPA routing.
|
||||
- **[[built-in processing|Built-in processing]]** — frontmatter, link resolution, drafts and the content index are built into Quartz (`configuration.frontmatter`, `links`, `drafts`, `contentIndex`) instead of plugins that broke the site when disabled.
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
---
|
||||
title: GitHub Action
|
||||
aliases:
|
||||
- action
|
||||
- quartz-community/action
|
||||
---
|
||||
|
||||
The [Quartz GitHub Action](https://github.com/quartz-community/action) builds a Quartz site from a repository that holds only your notes. You don't clone or fork Quartz: on every push, the action checks out a Quartz release, installs your plugins, builds the site and hands it to GitHub Pages.
|
||||
|
||||
> [!tip] Which setup do I need?
|
||||
>
|
||||
> - **Just notes** (an Obsidian vault, a `docs/` folder in a project, a notes repository): use the action. Your repository stays small, and new Quartz releases reach your site without `npx quartz upgrade`.
|
||||
> - **Changes to Quartz itself** (your own components, layouts or edits to Quartz's code): keep your own copy of Quartz, set up as in [[installation]], and deploy it as in [[hosting]].
|
||||
>
|
||||
> Both build the same site from the same `quartz.config.yaml`. The action needs Quartz 5.4.0 or later.
|
||||
|
||||
## Set it up
|
||||
|
||||
Your repository needs only your notes:
|
||||
|
||||
```
|
||||
content/ your notes (or docs/)
|
||||
quartz.config.yaml your configuration (optional)
|
||||
quartz.lock.json your pinned plugins (optional)
|
||||
```
|
||||
|
||||
1. Create `.github/workflows/deploy.yml`:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
name: Deploy Quartz site to GitHub Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0 # the full history, for created and modified dates
|
||||
- uses: quartz-community/action@v1
|
||||
|
||||
deploy:
|
||||
needs: build
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v5
|
||||
```
|
||||
|
||||
Change `main` if your notes live on another branch.
|
||||
|
||||
2. In your repository's **Settings**, under **Pages**, set **Source** to **GitHub Actions**.
|
||||
3. Push. The site is published at `<github-username>.github.io/<repository-name>`.
|
||||
|
||||
With only `content/`, the site uses Quartz's [[configuration#Extending the default configuration|default configuration]], titled with your repository's name, at its GitHub Pages address.
|
||||
|
||||
### Where your notes are
|
||||
|
||||
The action reads your notes from `content/`, or from `docs/` when there is no `content/`. For notes elsewhere, set `directory`, such as `.` for an Obsidian vault at the repository root:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
directory: .
|
||||
```
|
||||
|
||||
By default Quartz skips the `.obsidian`, `private` and `templates` folders, and files your `.gitignore` ignores. See [[private pages]] for keeping other notes off the site.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set your configuration in the workflow, in a `quartz.config.yaml` file, or both. Both take the same YAML as described in [[configuration]].
|
||||
|
||||
### In `quartz.config.yaml`
|
||||
|
||||
Start from Quartz's defaults with `extends: default` and write down only what you change:
|
||||
|
||||
```yaml title="quartz.config.yaml"
|
||||
extends: default
|
||||
configuration:
|
||||
pageTitle: My notes
|
||||
baseUrl: me.github.io/notes
|
||||
plugins:
|
||||
- source: "@quartz-community/graph"
|
||||
enabled: false # turn off a default plugin
|
||||
- source: github:me/my-plugin # add one
|
||||
enabled: true
|
||||
```
|
||||
|
||||
A full config without `extends` works too, but then changes to Quartz's defaults in later releases don't reach your site. Put the file elsewhere with the `config` input (for example `config: docs/quartz.config.yaml`).
|
||||
|
||||
### In the workflow
|
||||
|
||||
`configuration` takes the same YAML, applied on top of your `quartz.config.yaml`, or on top of Quartz's defaults when there is none:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
configuration: |
|
||||
configuration:
|
||||
pageTitle: My notes
|
||||
plugins:
|
||||
- source: "@quartz-community/graph"
|
||||
enabled: false
|
||||
```
|
||||
|
||||
This way a repository needs no Quartz files at all. With a config file, it's handy to change one setting for one workflow, such as the `baseUrl` of a preview build.
|
||||
|
||||
### The site's address
|
||||
|
||||
Without a config file, `baseUrl` is your repository's GitHub Pages address (`owner.github.io/repository`). For a custom domain, set `base-url` (or `baseUrl` in your configuration), and add the domain in your repository's Pages settings as described in [[hosting#Custom Domain|Custom Domain]]:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
base-url: notes.example.com
|
||||
```
|
||||
|
||||
## Plugins and `quartz.lock.json`
|
||||
|
||||
The default plugins ship with Quartz. Other plugins, from GitHub or npm, are installed on every build. `quartz.lock.json` is optional: it pins each of them to an exact commit or version, so every build uses the same plugins. Without it, the action installs each one at its latest release.
|
||||
|
||||
To create or update the lockfile, run the [[cli/plugin|plugin commands]] with `--config` pointing at your site, from any Quartz 5.4.0 or later checkout:
|
||||
|
||||
```shell
|
||||
npx quartz plugin install --config ../my-notes/quartz.config.yaml # pin what the config lists
|
||||
npx quartz plugin install --config ../my-notes/quartz.config.yaml --latest # update the pins
|
||||
```
|
||||
|
||||
The lockfile is written next to `quartz.config.yaml`. Commit it.
|
||||
|
||||
## Favicon, images and custom styles
|
||||
|
||||
The action copies these from your repository over Quartz's own before building, if they exist:
|
||||
|
||||
- `quartz/static/`: the favicon (`icon.png`), the default social image (`og-image.png`) and other files served from `static/`
|
||||
- `quartz/styles/custom.scss`: your custom styles, such as overrides for an [[configuration#General Configuration|Obsidian theme's colours]]
|
||||
|
||||
## Choosing a Quartz version
|
||||
|
||||
The action builds with the newest Quartz 5 release by default, so fixes and new features reach your site on its next build. For a site that doesn't change when Quartz releases a new version, pin one:
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
- uses: quartz-community/action@v1
|
||||
with:
|
||||
quartz-version: 5.4.1
|
||||
```
|
||||
|
||||
`quartz-version` also takes a tag, branch or commit of [jackyzha0/quartz](https://github.com/jackyzha0/quartz). Read [[upgrading]] before raising a pinned version.
|
||||
|
||||
## Inputs
|
||||
|
||||
| Input | Default | Description |
|
||||
| ----------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `quartz-version` | `latest` | Quartz release to build with: `latest` (the newest 5.x release), a version, or a tag, branch or commit |
|
||||
| `directory` | `content`, else `docs` | Content folder, relative to the repository root (`.` for the root itself) |
|
||||
| `config` | `quartz.config.yaml` | Config file, relative to the repository root (optional). `quartz.lock.json` is read from the same folder |
|
||||
| `configuration` | | Configuration as YAML: on top of the config file, or instead of one (then it extends `default` unless it says so) |
|
||||
| `base-url` | | The site's address, such as `notes.example.com`. Without a config file, the repository's GitHub Pages address |
|
||||
| `output` | outside the repository | Folder the site is built into, relative to the repository root. Keep it outside the content folder |
|
||||
| `node-version` | `24` | Node.js version (Quartz needs 22.22 or later) |
|
||||
| `cache` | `true` | Cache npm downloads and installed plugins between runs |
|
||||
| `upload-pages-artifact` | `true` | Upload the site as a GitHub Pages artifact for `actions/deploy-pages`. Set to `false` to deploy it some other way |
|
||||
|
||||
The action's outputs are `quartz-version` (the version the site was built with) and `output` (the absolute path of the built site). With `upload-pages-artifact: false`, deploy the folder from `output` to any host in a later step.
|
||||
|
||||
## Moving from your own copy of Quartz
|
||||
|
||||
If your site is a copy of Quartz (from the template or a fork), you can move it to the action:
|
||||
|
||||
1. Keep `content/`, `quartz.config.yaml`, `quartz.lock.json`, and any changes to `quartz/static/` and `quartz/styles/custom.scss`. Changes to other Quartz files aren't used by the action.
|
||||
2. Optionally, shrink `quartz.config.yaml` to `extends: default` and your changes (see [[configuration#Extending the default configuration]]). `npx quartz plugin list` and `npx quartz build --verbose` in your copy show what the site uses.
|
||||
3. Replace your deploy workflow with the one above.
|
||||
|
||||
Your notes and settings can stay in the same repository, or move to a new one that holds only them.
|
||||
+14
-8
@@ -6,6 +6,9 @@ Quartz effectively turns your Markdown files and other resources into a bundle o
|
||||
|
||||
However, if you'd like to publish your site to the world, you need a way to host it online. This guide will detail how to deploy with common hosting providers but any service that allows you to deploy static HTML should work as well.
|
||||
|
||||
> [!tip] Only publishing notes?
|
||||
> If your repository holds just your notes (an Obsidian vault, a project's `docs/` folder) and not a copy of Quartz, the [[github-action|Quartz GitHub Action]] builds and deploys it to GitHub Pages without cloning Quartz. The rest of this page is for sites that are a copy of Quartz.
|
||||
|
||||
> [!warning]
|
||||
> The rest of this guide assumes that you've already created your own GitHub repository for Quartz. If you haven't already, follow the [[installation#Setting Up Your GitHub Repository|GitHub repository setup]] section of the installation guide.
|
||||
|
||||
@@ -43,6 +46,9 @@ To add a custom domain, check out [Cloudflare's documentation](https://developer
|
||||
|
||||
## GitHub Pages
|
||||
|
||||
> [!tip]
|
||||
> A repository with only your notes doesn't need the workflow below: use the [[github-action|Quartz GitHub Action]].
|
||||
|
||||
In your local Quartz, create a new file `.github/workflows/deploy.yml` at the root of the repository.
|
||||
|
||||
```yaml title=".github/workflows/deploy.yml"
|
||||
@@ -66,21 +72,21 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history for git info
|
||||
- uses: actions/setup-node@v6
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
- name: Cache dependencies
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/.npm
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-
|
||||
- name: Cache Quartz plugins
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: .quartz/plugins
|
||||
key: ${{ runner.os }}-plugins-${{ hashFiles('quartz.lock.json') }}
|
||||
@@ -93,7 +99,7 @@ jobs:
|
||||
- name: Build Quartz
|
||||
run: npx quartz build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: public
|
||||
|
||||
@@ -106,7 +112,7 @@ jobs:
|
||||
steps:
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
uses: actions/deploy-pages@v5
|
||||
```
|
||||
|
||||
Then:
|
||||
@@ -252,7 +258,7 @@ pages:
|
||||
- public
|
||||
```
|
||||
|
||||
When `.gitlab-ci.yaml` is committed, GitLab will build and deploy the website as a GitLab Page. You can find the url under `Deploy > Pages` in the sidebar.
|
||||
When `.gitlab-ci.yml` is committed, GitLab will build and deploy the website as a GitLab Page. You can find the url under `Deploy > Pages` in the sidebar.
|
||||
|
||||
By default, the page is private and only visible when logged in to a GitLab account with access to the repository but can be opened in the settings under `Deploy` -> `Pages`.
|
||||
|
||||
@@ -302,7 +308,7 @@ Don't forget to activate brotli / gzip compression.
|
||||
|
||||
### Using Caddy
|
||||
|
||||
Here's and example of how to do this with Caddy:
|
||||
Here's an example of how to do this with Caddy:
|
||||
|
||||
```caddy title="Caddyfile"
|
||||
example.com {
|
||||
|
||||
@@ -33,6 +33,9 @@ Your site is now running at `http://localhost:8080`. From here:
|
||||
- **[[installation|Push to GitHub]]** with `npx quartz sync`
|
||||
- **[[hosting|Deploy]]** to GitHub Pages, Cloudflare, Netlify, or Vercel
|
||||
|
||||
> [!tip] Notes on GitHub
|
||||
> If your notes are already in a GitHub repository, the [[github-action|Quartz GitHub Action]] publishes them to GitHub Pages without cloning Quartz.
|
||||
|
||||
For the full walkthrough, see the [[getting-started/index|Getting Started]] guide.
|
||||
|
||||
### Returning User?
|
||||
|
||||
@@ -24,10 +24,13 @@ configuration:
|
||||
|
||||
Options:
|
||||
|
||||
- `markdownLinkResolution`: Sets the strategy for resolving Markdown paths, can be `"absolute"`, `"relative"` or `"shortest"` (default; the `crawl-links` plugin defaulted to `"absolute"`). You should use the same setting here as in [[Obsidian compatibility|Obsidian]].
|
||||
- `absolute`: Path relative to the root of the content folder.
|
||||
- `relative`: Path relative to the file you are linking from.
|
||||
- `shortest`: Name of the file. If this isn't enough to identify the file, use the full absolute path.
|
||||
- `markdownLinkResolution`: how link targets (in wikilinks and Markdown links) are read: `"shortest"` (default; the `crawl-links` plugin defaulted to `"absolute"`), `"absolute"` or `"relative"`.
|
||||
- `shortest`: as Obsidian resolves links, whatever its "New link format" setting. A target (`note`, `folder/note`) matches every page whose path ends with it, case-insensitively. With one match, the link goes there. With several, it goes to the page whose path is exactly the target, else to a page in the linking note's folder or below it, else to any other; among those, the page with the shortest path wins (Quartz breaks a tie alphabetically; Obsidian by its own file order). A target starting with `./` or `../` is a path from the linking note's folder, and one starting with `/` a path from the root of the content folder.
|
||||
- `absolute`: a target is a path from the root of the content folder, as Obsidian writes links with "Absolute path in vault". A bare name only reaches a note at the root.
|
||||
- `relative`: a target is a path from the linking note's folder, as Obsidian writes links with "Relative path to file".
|
||||
|
||||
Obsidian's "New link format" setting only decides how Obsidian _writes_ new links; it reads every link the same way, as `shortest` does. Keep `shortest` unless all links in your notes are full paths (`absolute`) or relative paths (`relative`). Under every setting, a target starting with `./` or `../` is a path from the linking note's folder.
|
||||
|
||||
- `prettyLinks`: If `true` (default), simplifies links by removing folder paths, making them more user friendly (e.g. `folder/deeply/nested/note` becomes `note`).
|
||||
- `openLinksInNewTab`: If `true`, configures external links to open in a new tab. Defaults to `false`.
|
||||
- `lazyLoad`: If `true`, adds lazy loading to resource elements (`img`, `video`, etc.) to improve page load performance. Defaults to `false`.
|
||||
|
||||
@@ -9,7 +9,7 @@ enabled: true
|
||||
required: false
|
||||
---
|
||||
|
||||
This plugin determines the created, modified, and published dates for a document using three potential data sources: frontmatter metadata, Git history, and the filesystem. See [[authoring content#Syntax]] for more information.
|
||||
This plugin determines the created, modified, and published dates for a document using three potential data sources: frontmatter metadata, Git history, and the filesystem. See [[getting-started/authoring-content#Syntax|authoring content]] for more information.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
@@ -11,7 +11,7 @@ required: false
|
||||
|
||||
This plugin generates descriptions that are used as metadata for the HTML `head`, the [[RSS Feed]] and in [[folder and tag listings]] if there is no main body content, the description is used as the text between the title and the listing.
|
||||
|
||||
If the frontmatter contains a `description` property, it is used (see [[authoring content#Syntax]]). Otherwise, the plugin builds one from the first sentences of the content.
|
||||
If the frontmatter contains a `description` property, it is used (see [[getting-started/authoring-content#Syntax|authoring content]]). Otherwise, the plugin builds one from the first sentences of the content.
|
||||
|
||||
> [!note]
|
||||
> For information on how to add, remove or configure plugins, see the [[configuration#Plugins|Configuration]] page.
|
||||
|
||||
@@ -16,7 +16,7 @@ enabled: true
|
||||
required: true
|
||||
---
|
||||
|
||||
Frontmatter parsing is [[built-in processing|built into Quartz]]: every page's frontmatter is parsed with [gray-matter](https://github.com/jonschlinkert/gray-matter) and normalised (see [[#Supported frontmatter]]). Displaying properties on the page is done by the optional `note-properties` plugin ([[#Properties panel]]). See [[authoring content#Syntax]], [[Obsidian compatibility]] and [[OxHugo compatibility]] for more information.
|
||||
Frontmatter parsing is [[built-in processing|built into Quartz]]: every page's frontmatter is parsed with [gray-matter](https://github.com/jonschlinkert/gray-matter) and normalised (see [[#Supported frontmatter]]). Displaying properties on the page is done by the optional `note-properties` plugin ([[#Properties panel]]). See [[getting-started/authoring-content#Syntax|authoring content]], [[Obsidian compatibility]] and [[OxHugo compatibility]] for more information.
|
||||
|
||||
## Parsing (built-in)
|
||||
|
||||
|
||||
Generated
+44
-44
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@jackyzha0/quartz",
|
||||
"version": "5.3.0",
|
||||
"version": "5.4.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@jackyzha0/quartz",
|
||||
"version": "5.3.0",
|
||||
"version": "5.4.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.8.0",
|
||||
@@ -18,7 +18,7 @@
|
||||
"@quartz-community/backlinks": "^1.0.4",
|
||||
"@quartz-community/bases-page": "^1.5.6",
|
||||
"@quartz-community/breadcrumbs": "^1.0.6",
|
||||
"@quartz-community/canvas-page": "^1.1.6",
|
||||
"@quartz-community/canvas-page": "^1.1.7",
|
||||
"@quartz-community/citations": "^1.0.1",
|
||||
"@quartz-community/cname": "^1.0.1",
|
||||
"@quartz-community/comments": "^1.0.3",
|
||||
@@ -31,23 +31,23 @@
|
||||
"@quartz-community/explicit-publish": "^1.2.0",
|
||||
"@quartz-community/explorer": "^1.2.5",
|
||||
"@quartz-community/favicon": "^1.0.1",
|
||||
"@quartz-community/folder-page": "^1.1.4",
|
||||
"@quartz-community/folder-page": "^1.1.5",
|
||||
"@quartz-community/footer": "^1.1.2",
|
||||
"@quartz-community/github-flavored-markdown": "^2.2.2",
|
||||
"@quartz-community/graph": "^1.0.9",
|
||||
"@quartz-community/graph": "^1.0.10",
|
||||
"@quartz-community/hard-line-breaks": "^1.1.0",
|
||||
"@quartz-community/latex": "^1.1.3",
|
||||
"@quartz-community/note-properties": "^1.2.4",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
|
||||
"@quartz-community/og-image": "^1.1.4",
|
||||
"@quartz-community/og-image": "^1.2.0",
|
||||
"@quartz-community/ox-hugo": "^1.0.4",
|
||||
"@quartz-community/page-title": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.3",
|
||||
"@quartz-community/recent-notes": "^1.0.3",
|
||||
"@quartz-community/roam": "^1.1.0",
|
||||
"@quartz-community/search": "^1.1.4",
|
||||
"@quartz-community/search": "^1.1.5",
|
||||
"@quartz-community/spacer": "^1.0.2",
|
||||
"@quartz-community/stacked-pages": "^1.0.4",
|
||||
"@quartz-community/stacked-pages": "^1.0.5",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.5",
|
||||
"@quartz-community/table-of-contents": "^1.0.6",
|
||||
"@quartz-community/tag-list": "^1.0.3",
|
||||
@@ -64,7 +64,7 @@
|
||||
"hast-util-to-html": "^9.0.7",
|
||||
"hast-util-to-jsx-runtime": "^2.3.6",
|
||||
"is-absolute-url": "^5.0.0",
|
||||
"isomorphic-git": "^1.36.3",
|
||||
"isomorphic-git": "^1.44.19",
|
||||
"js-yaml": "^5.5.0",
|
||||
"lightningcss": "^1.31.1",
|
||||
"micromorph": "^0.4.5",
|
||||
@@ -97,9 +97,9 @@
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.3.4",
|
||||
"@quartz-community/utils": "^1.3.5",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@types/source-map-support": "^0.5.10",
|
||||
@@ -2264,9 +2264,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/alias-redirects": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/alias-redirects/-/alias-redirects-1.0.4.tgz",
|
||||
"integrity": "sha512-DGlkfTtpG8TBI8zyibUq5XCK00gqEyG+nK8YfhNgnvIgUUKtO5Cdx5HSpI+K2a8bb0uT0zpeAUy/uwUp30EmLQ==",
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/alias-redirects/-/alias-redirects-1.0.5.tgz",
|
||||
"integrity": "sha512-S0MWQAPmV7vZm2tvklo9+r5MrkQcqDeAcTXqlBhUSAv8CmOCIxkq6Iuca1Pd84Cda17A2A3nQ8fh8GLbr5WdxQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2383,9 +2383,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/canvas-page": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.6.tgz",
|
||||
"integrity": "sha512-Cuu3xxC1PCKM5+ixO58cnNmK0So9RHnE1bxVLPW619b0tCL2ZyuN4QQK4yCN7ia8N6uiLyI+jqAALMS1+tl9fA==",
|
||||
"version": "1.1.7",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/canvas-page/-/canvas-page-1.1.7.tgz",
|
||||
"integrity": "sha512-I2I5JqqJ6PGnnwq57KI27Z643o/yUrxl654uwV8m+hFPmaN1iG8OQD7597JDHYXrwWCKWnNi23Wy3HXFu0yPUg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2664,9 +2664,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/folder-page": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/folder-page/-/folder-page-1.1.4.tgz",
|
||||
"integrity": "sha512-aEaXi5qJdWPMMvtBakaVw/wDU/iVf5ujW1hMnBxDJyCDXF9FRdk1njeFi+Op299y5SWnF7+ruLjhraqeaYLnCA==",
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/folder-page/-/folder-page-1.1.5.tgz",
|
||||
"integrity": "sha512-Uxlno9jMCDzlKbF5HkrvUDzg0zxqabUhIfANsfC1RlfSq6cNmuXUYwe45vhkEp/KDOM8bBcfuHKARO3OqABzGA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2734,9 +2734,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/graph": {
|
||||
"version": "1.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.9.tgz",
|
||||
"integrity": "sha512-7t6v0i9dPr8JIWRQEalszHk25pmhapns/mD18zyt0P1EwbZrU8Kbc5l6nXFM7jSq/pfigDvo9GmcNFFtTMYK1Q==",
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/graph/-/graph-1.0.10.tgz",
|
||||
"integrity": "sha512-UkqWEI48wmxLQPS+HNW4Pm0GnuUpcn7IfZ3ufcg1S4/lVqrdrofj7SioXDm7djuwr/wsLPDsdC1YBCwct/Eu5w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2853,9 +2853,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/og-image": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/og-image/-/og-image-1.1.4.tgz",
|
||||
"integrity": "sha512-aJyXYMjIPrj3M3jFoYyqW/YODKmSoJP+bbQ5LyH0FnpuWGIGDBPVRqYmx5qUuiVjc5SMiVMMf8AyWuH63nCbUQ==",
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/og-image/-/og-image-1.2.0.tgz",
|
||||
"integrity": "sha512-fVvrOwog7QTGf7X0iNPFAmM5nRvK4Mdh9XQqpE8PDQ3X9fbHcnCq++H1H+a0xXjiB1BADKuT2146pjNmOkPEaw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -2979,9 +2979,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/remark-obsidian": {
|
||||
"version": "2.2.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.5.tgz",
|
||||
"integrity": "sha512-xlJX+6XIWEBCPnJ4Mg8Xnrxeh2+pq0XAKUWXGOEY0kHNf2uDsiM5VRTd15/4jR1J2FN2KmOAB7jV+8J0xSlnqg==",
|
||||
"version": "2.2.6",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/remark-obsidian/-/remark-obsidian-2.2.6.tgz",
|
||||
"integrity": "sha512-hDxyFiA5SYIcsO1i3vnlMQEryoev2RtFy9UZ9MGNfANxiWypxCG/uWUjA+uiISMJgHSRk/CpWcn7lTGGvMVT3A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/mdast": "^4.0.0",
|
||||
@@ -3019,9 +3019,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/search": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/search/-/search-1.1.4.tgz",
|
||||
"integrity": "sha512-s02rNbjLkg4rVNdA0Pr2LHlGK1zn0PcS2+mBoyWqhZ4vZraGKgLpbAUiDgXD740GU630vcpEwmtT0FNWbgzl9g==",
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/search/-/search-1.1.5.tgz",
|
||||
"integrity": "sha512-9qgJsfOlqBPP41ICDOmmHOYiJbjlIMYm6EduvjS4t32YWglRJpO5l0Dle6A8VYmt7PW6qrAkh2EU7TvwCUU2Aw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -3062,9 +3062,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/stacked-pages": {
|
||||
"version": "1.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/stacked-pages/-/stacked-pages-1.0.4.tgz",
|
||||
"integrity": "sha512-XQsi9CwReWxr7c6e1uWHpYYegQfpaL+sPPASkM+RVX0pw21V9aYpMy0HRFWpbyJnpIM847rVPfZ6W3IH3Db/mw==",
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/stacked-pages/-/stacked-pages-1.0.5.tgz",
|
||||
"integrity": "sha512-sUDlcgREgWyttDg4A6Xp6i3s0jjLzO0g/pvP2a5KSYfNtsN9djbvwaPaewV9e/dn92VyTWrKsXd7K05yTCcFQw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0",
|
||||
@@ -3230,9 +3230,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@quartz-community/utils": {
|
||||
"version": "1.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.4.tgz",
|
||||
"integrity": "sha512-S1zlszf1jcHXcWXnlow/VxW3kKlTEWWNGQmWP07b8vAOB8lAIkeYRR5KoUA0TdjZPgN5dRaFHaAhv6sC2g/4Gw==",
|
||||
"version": "1.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@quartz-community/utils/-/utils-1.3.5.tgz",
|
||||
"integrity": "sha512-ZN8nlrjrwnrGlOfCArOPqOhAJNiKqhpPp6sqsN31ZoOjCQkExqd5f1+vMpy48SezjFup+k9XJ+yPHRkaGjtPIg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@quartz-community/types": "^1.0.0"
|
||||
@@ -3333,9 +3333,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "26.6.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
|
||||
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
|
||||
"version": "26.6.11",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
|
||||
"integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -5125,9 +5125,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/isomorphic-git": {
|
||||
"version": "1.44.18",
|
||||
"resolved": "https://registry.npmjs.org/isomorphic-git/-/isomorphic-git-1.44.18.tgz",
|
||||
"integrity": "sha512-+VgjSGkpuLHG/R8oYcPsRUCcr0ppbCfm3Eiws94I69Xzq8tc1Ar40ahngU52niIYejuTtWrbs/o0padH4SxKqQ==",
|
||||
"version": "1.44.19",
|
||||
"resolved": "https://registry.npmjs.org/isomorphic-git/-/isomorphic-git-1.44.19.tgz",
|
||||
"integrity": "sha512-s4g8B1KBBYMop1dU/QqratyTjdhNTPMTP9dOBurGto8lBg6fRD4J5osy9fEY+vOj8W4/QpYMs6bzwhtM5K+6Vg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"async-lock": "^1.4.1",
|
||||
|
||||
+10
-10
@@ -2,7 +2,7 @@
|
||||
"name": "@jackyzha0/quartz",
|
||||
"description": "🌱 publish your digital garden and notes as a website",
|
||||
"private": true,
|
||||
"version": "5.3.0",
|
||||
"version": "5.4.1",
|
||||
"type": "module",
|
||||
"author": "jackyzha0 <j.zhao2k19@gmail.com>",
|
||||
"license": "MIT",
|
||||
@@ -48,7 +48,7 @@
|
||||
"@quartz-community/backlinks": "^1.0.4",
|
||||
"@quartz-community/bases-page": "^1.5.6",
|
||||
"@quartz-community/breadcrumbs": "^1.0.6",
|
||||
"@quartz-community/canvas-page": "^1.1.6",
|
||||
"@quartz-community/canvas-page": "^1.1.7",
|
||||
"@quartz-community/citations": "^1.0.1",
|
||||
"@quartz-community/cname": "^1.0.1",
|
||||
"@quartz-community/comments": "^1.0.3",
|
||||
@@ -61,23 +61,23 @@
|
||||
"@quartz-community/explicit-publish": "^1.2.0",
|
||||
"@quartz-community/explorer": "^1.2.5",
|
||||
"@quartz-community/favicon": "^1.0.1",
|
||||
"@quartz-community/folder-page": "^1.1.4",
|
||||
"@quartz-community/folder-page": "^1.1.5",
|
||||
"@quartz-community/footer": "^1.1.2",
|
||||
"@quartz-community/github-flavored-markdown": "^2.2.2",
|
||||
"@quartz-community/graph": "^1.0.9",
|
||||
"@quartz-community/graph": "^1.0.10",
|
||||
"@quartz-community/hard-line-breaks": "^1.1.0",
|
||||
"@quartz-community/latex": "^1.1.3",
|
||||
"@quartz-community/note-properties": "^1.2.4",
|
||||
"@quartz-community/obsidian-flavored-markdown": "^2.5.4",
|
||||
"@quartz-community/og-image": "^1.1.4",
|
||||
"@quartz-community/og-image": "^1.2.0",
|
||||
"@quartz-community/ox-hugo": "^1.0.4",
|
||||
"@quartz-community/page-title": "^1.0.2",
|
||||
"@quartz-community/reader-mode": "^1.0.3",
|
||||
"@quartz-community/recent-notes": "^1.0.3",
|
||||
"@quartz-community/roam": "^1.1.0",
|
||||
"@quartz-community/search": "^1.1.4",
|
||||
"@quartz-community/search": "^1.1.5",
|
||||
"@quartz-community/spacer": "^1.0.2",
|
||||
"@quartz-community/stacked-pages": "^1.0.4",
|
||||
"@quartz-community/stacked-pages": "^1.0.5",
|
||||
"@quartz-community/syntax-highlighting": "^1.0.5",
|
||||
"@quartz-community/table-of-contents": "^1.0.6",
|
||||
"@quartz-community/tag-list": "^1.0.3",
|
||||
@@ -94,7 +94,7 @@
|
||||
"hast-util-to-html": "^9.0.7",
|
||||
"hast-util-to-jsx-runtime": "^2.3.6",
|
||||
"is-absolute-url": "^5.0.0",
|
||||
"isomorphic-git": "^1.36.3",
|
||||
"isomorphic-git": "^1.44.19",
|
||||
"js-yaml": "^5.5.0",
|
||||
"lightningcss": "^1.31.1",
|
||||
"micromorph": "^0.4.5",
|
||||
@@ -124,9 +124,9 @@
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^3.0.3",
|
||||
"@quartz-community/types": "^1.3.1",
|
||||
"@quartz-community/utils": "^1.3.4",
|
||||
"@quartz-community/utils": "^1.3.5",
|
||||
"@types/hast": "^3.0.4",
|
||||
"@types/node": "^26.5.1",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/pretty-time": "^1.1.5",
|
||||
"@types/semver": "^7.7.1",
|
||||
"@types/source-map-support": "^0.5.10",
|
||||
|
||||
@@ -7,6 +7,8 @@ if (major < 22 || (major === 22 && minor < 22)) {
|
||||
)
|
||||
process.exit(1)
|
||||
}
|
||||
import { existsSync } from "fs"
|
||||
import { resolve } from "path"
|
||||
import yargs from "yargs"
|
||||
import { hideBin } from "yargs/helpers"
|
||||
import {
|
||||
@@ -121,6 +123,24 @@ yargs(hideBin(process.argv))
|
||||
(yargs) => {
|
||||
return (
|
||||
yargs
|
||||
// like `build --config`: plugin commands read and write that config, and the
|
||||
// quartz.lock.json next to it (cli/lockfile-path.js)
|
||||
.option("config", {
|
||||
string: true,
|
||||
alias: ["C"],
|
||||
global: true,
|
||||
describe:
|
||||
"path to the config file (default: ./quartz.config.yaml); quartz.lock.json is next to it",
|
||||
})
|
||||
.middleware((argv) => {
|
||||
if (!argv.config) return
|
||||
const resolved = resolve(argv.config)
|
||||
if (!existsSync(resolved)) {
|
||||
console.error(`Config file not found: ${resolved}`)
|
||||
process.exit(1)
|
||||
}
|
||||
process.env.QUARTZ_CONFIG_PATH = resolved
|
||||
})
|
||||
.command(
|
||||
"install [names..]",
|
||||
"Install plugins from lockfile or config",
|
||||
@@ -335,6 +355,17 @@ yargs(hideBin(process.argv))
|
||||
},
|
||||
)
|
||||
.showHelpOnFail(true)
|
||||
.fail((msg, err, y) => {
|
||||
// A mistake in quartz.config.yaml (an `extends` error names the file and the key): the
|
||||
// message says what to fix, so print it without the usage text, which is about arguments.
|
||||
if (err?.name === "ConfigExtendsError") {
|
||||
console.error(`✗ ${err.message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
y.showHelp()
|
||||
console.error(err ?? msg)
|
||||
process.exit(1)
|
||||
})
|
||||
.help()
|
||||
.strict()
|
||||
.demandCommand().argv
|
||||
+39
-19
@@ -10,7 +10,7 @@ import { parseMarkdown } from "./processors/parse"
|
||||
import { filterContent } from "./processors/filter"
|
||||
import { emitContent } from "./processors/emit"
|
||||
import cfg from "../quartz"
|
||||
import { FilePath, joinSegments, slugifyFilePath } from "./util/path"
|
||||
import { FilePath, FullSlug, joinSegments, slugifyFilePath } from "./util/path"
|
||||
import { detectSlugCollisions, formatCollisionWarning } from "./util/slugCollisions"
|
||||
import chokidar from "chokidar"
|
||||
import { ProcessedContent } from "./plugins/vfile"
|
||||
@@ -29,42 +29,62 @@ import { prepareContentIndex } from "./plugins/builtins/contentIndex"
|
||||
import { filteredBy, printDiagnosticsSummary, warn } from "./util/diagnostics"
|
||||
import { LinksInstance, removedPages } from "./plugins/builtins/links"
|
||||
import { collectPermalinks } from "./util/permalinks"
|
||||
import { readFrontmatterData } from "./plugins/builtins/frontmatter"
|
||||
import { collectAliases } from "./util/aliases"
|
||||
import { aliasSlugsOf, readFrontmatterData } from "./plugins/builtins/frontmatter"
|
||||
import { ChangeRecord, clearChangeRecord } from "./util/incremental"
|
||||
import { diffContentFiles, pollingEnabled } from "./util/contentWatcher"
|
||||
|
||||
/**
|
||||
* Every page's address: permalinks (frontmatter `permalink`, read up front so links can resolve
|
||||
* to them) and the slugified paths of all files. A permalinked note's file path stays in
|
||||
* `allSlugs`: it becomes a redirect to the permalink.
|
||||
* `allSlugs`: it becomes a redirect to the permalink. Frontmatter `aliases` are read up front
|
||||
* too (`ctx.aliases`), so links that only an alias matches go to the page (util/aliases.ts).
|
||||
*/
|
||||
function updateSlugs(ctx: BuildCtx, allFiles: string[]): void {
|
||||
const frontmatter = ctx.cfg.configuration.frontmatter
|
||||
const enabled =
|
||||
frontmatter !== false && (typeof frontmatter !== "object" || frontmatter.enabled !== false)
|
||||
const options = typeof frontmatter === "object" ? frontmatter : {}
|
||||
const markdown = allFiles.filter((fp) => fp.endsWith(".md"))
|
||||
// frontmatter of the files that may set a permalink or aliases, read once
|
||||
const data = new Map<string, Record<string, unknown>>()
|
||||
if (enabled) {
|
||||
for (const fp of markdown) {
|
||||
let source: Buffer
|
||||
try {
|
||||
source = fs.readFileSync(path.join(ctx.argv.directory, fp))
|
||||
} catch {
|
||||
continue // an unreadable file is reported when the file is parsed
|
||||
}
|
||||
if (!source.includes("permalink") && !source.includes("alias")) continue
|
||||
try {
|
||||
data.set(fp, readFrontmatterData(source, options))
|
||||
} catch {
|
||||
// reported when the file is parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.permalinks = enabled
|
||||
? collectPermalinks({
|
||||
files: allFiles.filter((fp) => fp.endsWith(".md")),
|
||||
permalinkOf: (fp) => {
|
||||
let source: Buffer
|
||||
try {
|
||||
source = fs.readFileSync(path.join(ctx.argv.directory, fp))
|
||||
} catch {
|
||||
return undefined // an unreadable file is reported when the file is parsed
|
||||
}
|
||||
if (!source.includes("permalink")) return undefined
|
||||
try {
|
||||
return readFrontmatterData(source, options).permalink
|
||||
} catch {
|
||||
return undefined // reported when the file is parsed
|
||||
}
|
||||
},
|
||||
files: markdown,
|
||||
permalinkOf: (fp) => data.get(fp)?.permalink,
|
||||
warn: (message) => warn({ area: "permalinks", message }),
|
||||
})
|
||||
: {}
|
||||
ctx.aliases = enabled
|
||||
? collectAliases({
|
||||
files: allFiles,
|
||||
aliasesOf: (fp) => {
|
||||
const fm = data.get(fp)
|
||||
return fm ? aliasSlugsOf(fm) : []
|
||||
},
|
||||
permalinks: ctx.permalinks,
|
||||
})
|
||||
: {}
|
||||
const pathSlugs = allFiles.map((fp) => slugifyFilePath(fp as FilePath))
|
||||
ctx.allSlugs = [...new Set([...pathSlugs, ...Object.values(ctx.permalinks)])]
|
||||
ctx.allSlugs = [
|
||||
...new Set([...pathSlugs, ...Object.values(ctx.permalinks), ...Object.keys(ctx.aliases)]),
|
||||
] as FullSlug[]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export const LOCKFILE_NAME: string
|
||||
export function resolveLockfilePath(configPath: string, cwd?: string): string
|
||||
export function currentLockfilePath(cwd?: string): string
|
||||
@@ -0,0 +1,29 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
|
||||
export const LOCKFILE_NAME = "quartz.lock.json"
|
||||
|
||||
/**
|
||||
* Where quartz.lock.json is: next to the config file Quartz uses (`--config` / `-C`, or
|
||||
* QUARTZ_CONFIG_PATH), so a repository that holds only a site's content, config and lockfile
|
||||
* (such as one the GitHub Action builds) keeps its pins with its config.
|
||||
*
|
||||
* With the config in Quartz's own folder (the usual setup) that is Quartz's folder, as before.
|
||||
* A config elsewhere whose folder has no lockfile yet keeps using an existing one in Quartz's
|
||||
* folder (`cwd`), so setups from before this change still find their pins.
|
||||
*/
|
||||
export function resolveLockfilePath(configPath, cwd = process.cwd()) {
|
||||
const besideConfig = path.join(path.dirname(path.resolve(configPath)), LOCKFILE_NAME)
|
||||
const inQuartz = path.join(cwd, LOCKFILE_NAME)
|
||||
if (besideConfig !== inQuartz && !fs.existsSync(besideConfig) && fs.existsSync(inQuartz)) {
|
||||
return inQuartz
|
||||
}
|
||||
return besideConfig
|
||||
}
|
||||
|
||||
/** The lockfile for the config this process uses: QUARTZ_CONFIG_PATH's, else Quartz's folder. */
|
||||
export function currentLockfilePath(cwd = process.cwd()) {
|
||||
return process.env.QUARTZ_CONFIG_PATH
|
||||
? resolveLockfilePath(process.env.QUARTZ_CONFIG_PATH, cwd)
|
||||
: path.join(cwd, LOCKFILE_NAME)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import test, { describe, afterEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { currentLockfilePath, resolveLockfilePath } from "./lockfile-path.js"
|
||||
|
||||
describe("resolveLockfilePath", () => {
|
||||
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "quartz-lockfile-path-"))
|
||||
|
||||
test("the lockfile is next to the config", () => {
|
||||
const quartz = tmp()
|
||||
const site = tmp()
|
||||
assert.strictEqual(
|
||||
resolveLockfilePath(path.join(site, "quartz.config.yaml"), quartz),
|
||||
path.join(site, "quartz.lock.json"),
|
||||
)
|
||||
// the usual setup: the config in Quartz's folder
|
||||
assert.strictEqual(
|
||||
resolveLockfilePath(path.join(quartz, "quartz.config.yaml"), quartz),
|
||||
path.join(quartz, "quartz.lock.json"),
|
||||
)
|
||||
})
|
||||
|
||||
test("an existing lockfile in Quartz's folder is kept until the config's folder has one", () => {
|
||||
const quartz = tmp()
|
||||
const site = tmp()
|
||||
fs.writeFileSync(path.join(quartz, "quartz.lock.json"), "{}")
|
||||
const config = path.join(site, "quartz.config.yaml")
|
||||
assert.strictEqual(resolveLockfilePath(config, quartz), path.join(quartz, "quartz.lock.json"))
|
||||
fs.writeFileSync(path.join(site, "quartz.lock.json"), "{}")
|
||||
assert.strictEqual(resolveLockfilePath(config, quartz), path.join(site, "quartz.lock.json"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("currentLockfilePath", () => {
|
||||
const saved = process.env.QUARTZ_CONFIG_PATH
|
||||
afterEach(() => {
|
||||
if (saved === undefined) delete process.env.QUARTZ_CONFIG_PATH
|
||||
else process.env.QUARTZ_CONFIG_PATH = saved
|
||||
})
|
||||
|
||||
test("follows QUARTZ_CONFIG_PATH, else Quartz's folder", () => {
|
||||
const site = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-lockfile-current-"))
|
||||
delete process.env.QUARTZ_CONFIG_PATH
|
||||
assert.strictEqual(currentLockfilePath("/q"), path.join("/q", "quartz.lock.json"))
|
||||
process.env.QUARTZ_CONFIG_PATH = path.join(site, "quartz.config.yaml")
|
||||
assert.strictEqual(currentLockfilePath("/q"), path.join(site, "quartz.lock.json"))
|
||||
})
|
||||
})
|
||||
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
/** A quartz.lock.json entry pinning an npm plugin (see npm-plugins.js). */
|
||||
export interface NpmLockEntry {
|
||||
source: unknown
|
||||
version: string
|
||||
integrity?: string
|
||||
resolved?: string
|
||||
installedAt?: string
|
||||
}
|
||||
/** What installing an npm plugin returns: the fields its lock entry pins. */
|
||||
export interface NpmInstallResult {
|
||||
version: string
|
||||
integrity?: string
|
||||
resolved?: string
|
||||
}
|
||||
export function npmPackageName(spec: string): string
|
||||
export function isNpmLockEntry(entry: unknown): entry is NpmLockEntry
|
||||
export function readNpmLockEntry(name: string, lockfilePath: string): NpmLockEntry | undefined
|
||||
export function isHostDependency(name: string, root?: string): boolean
|
||||
export function npmPluginDir(name: string, pluginsDir?: string): string
|
||||
export function installedNpmPluginVersion(name: string, pluginsDir: string): string | null
|
||||
export function isPinnedNpmPluginInstalled(name: string, pluginsDir: string, root?: string): boolean
|
||||
export function latestNpmVersion(name: string): string
|
||||
export function latestNpmVersionAsync(name: string): Promise<string>
|
||||
export function listPluginDirNames(pluginsDir: string): string[]
|
||||
export function installNpmPlugin(
|
||||
name: string,
|
||||
options: {
|
||||
version?: string
|
||||
integrity?: string
|
||||
pluginsDir: string
|
||||
verbose?: boolean
|
||||
/** Runs npm (tests pass a fake). */
|
||||
run?: (args: string[], options: { cwd: string; stdio?: string; timeout?: number }) => unknown
|
||||
},
|
||||
): NpmInstallResult
|
||||
export function removeNpmPlugin(name: string, pluginsDir: string): void
|
||||
export function nextNpmLockEntry(
|
||||
lockEntry: unknown,
|
||||
source: unknown,
|
||||
result: NpmInstallResult,
|
||||
): NpmLockEntry
|
||||
export function ensureNpmPlugin(
|
||||
name: string,
|
||||
options: {
|
||||
lockEntry?: NpmLockEntry
|
||||
fallbackVersion?: string
|
||||
pluginsDir: string
|
||||
verbose?: boolean
|
||||
},
|
||||
): NpmInstallResult | null
|
||||
@@ -0,0 +1,289 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { assertNpmSpec, npm, npmAsync } from "./subprocess.js"
|
||||
|
||||
/**
|
||||
* npm plugins that Quartz's package.json doesn't list are pinned in quartz.lock.json and
|
||||
* installed into .quartz/plugins/<@scope>/<name>, like Git plugins, instead of node_modules:
|
||||
*
|
||||
* - `npm install` / `npm ci` remove packages package.json doesn't list, so a plugin installed
|
||||
* into node_modules without saving would disappear; saving it to Quartz's package.json made
|
||||
* `npx quartz upgrade` conflict on the user's additions.
|
||||
* - A site whose repository holds only its content, config and lockfile (the GitHub Action)
|
||||
* pins its npm plugins in a file it owns.
|
||||
*
|
||||
* A plugin in package.json (Quartz's own default plugins, or one the user `npm install`ed) is
|
||||
* versioned there and loaded from node_modules, as before: package.json wins.
|
||||
*
|
||||
* Lock entry: `{ source, version, integrity, resolved, installedAt }` (no `commit`, which every
|
||||
* Git or local entry has).
|
||||
*/
|
||||
|
||||
const NPM_INSTALL_TIMEOUT_MS = 300_000
|
||||
const NPM_VIEW_TIMEOUT_MS = 60_000
|
||||
|
||||
/** `@scope/name` of an npm plugin source (a version suffix, `@scope/name@1.2`, is dropped). */
|
||||
export function npmPackageName(spec) {
|
||||
const at = spec.lastIndexOf("@")
|
||||
return at > 0 ? spec.slice(0, at) : spec
|
||||
}
|
||||
|
||||
/** Whether a lock entry pins an npm plugin. */
|
||||
export function isNpmLockEntry(entry) {
|
||||
return (
|
||||
!!entry &&
|
||||
typeof entry === "object" &&
|
||||
entry.commit === undefined &&
|
||||
typeof entry.version === "string"
|
||||
)
|
||||
}
|
||||
|
||||
/** The npm lock entry for `name` in the lockfile at `lockfilePath`, if there is one. */
|
||||
export function readNpmLockEntry(name, lockfilePath) {
|
||||
try {
|
||||
const entry = JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))?.plugins?.[name]
|
||||
return isNpmLockEntry(entry) ? entry : undefined
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether `name` is a dependency in package.json at `root` (Quartz's directory). */
|
||||
export function isHostDependency(name, root = process.cwd()) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8"))
|
||||
return [
|
||||
pkg.dependencies,
|
||||
pkg.devDependencies,
|
||||
pkg.optionalDependencies,
|
||||
pkg.peerDependencies,
|
||||
].some((deps) => deps && Object.hasOwn(deps, name))
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a pinned npm plugin is installed: `<pluginsDir>/@scope/name`. */
|
||||
export function npmPluginDir(name, pluginsDir = path.join(process.cwd(), ".quartz", "plugins")) {
|
||||
return path.join(pluginsDir, ...name.split("/"))
|
||||
}
|
||||
|
||||
/** The version of the pinned npm plugin installed in `pluginsDir`, or null. */
|
||||
export function installedNpmPluginVersion(name, pluginsDir) {
|
||||
try {
|
||||
const pkg = JSON.parse(
|
||||
fs.readFileSync(path.join(npmPluginDir(name, pluginsDir), "package.json"), "utf-8"),
|
||||
)
|
||||
return pkg.name === name && typeof pkg.version === "string" ? pkg.version : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the npm plugin `name` is pinned in quartz.lock.json and loaded from
|
||||
* `<pluginsDir>/@scope/name` (rather than from node_modules): it is not in package.json, and it
|
||||
* is installed there.
|
||||
*/
|
||||
export function isPinnedNpmPluginInstalled(name, pluginsDir, root = process.cwd()) {
|
||||
return !isHostDependency(name, root) && installedNpmPluginVersion(name, pluginsDir) !== null
|
||||
}
|
||||
|
||||
/** The version npm's `latest` tag points at. */
|
||||
export function latestNpmVersion(name) {
|
||||
const out = npm(["view", assertNpmSpec(name), "version", "--json"], {
|
||||
timeout: NPM_VIEW_TIMEOUT_MS,
|
||||
})
|
||||
const version = JSON.parse(out)
|
||||
if (typeof version !== "string") throw new Error(`npm view ${name} returned no version`)
|
||||
return version
|
||||
}
|
||||
|
||||
/** The version npm's `latest` tag points at, without blocking (for status checks in parallel). */
|
||||
export async function latestNpmVersionAsync(name) {
|
||||
const { stdout } = await npmAsync(["view", assertNpmSpec(name), "version", "--json"], {
|
||||
timeout: NPM_VIEW_TIMEOUT_MS,
|
||||
})
|
||||
const version = JSON.parse(stdout)
|
||||
if (typeof version !== "string") throw new Error(`npm view ${name} returned no version`)
|
||||
return version
|
||||
}
|
||||
|
||||
/**
|
||||
* The directories `pluginsDir` holds plugins in: `name` for Git and local plugins,
|
||||
* `@scope/name` for pinned npm plugins.
|
||||
*/
|
||||
export function listPluginDirNames(pluginsDir) {
|
||||
if (!fs.existsSync(pluginsDir)) return []
|
||||
const isDir = (p) => {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const names = []
|
||||
for (const entry of fs.readdirSync(pluginsDir)) {
|
||||
const full = path.join(pluginsDir, entry)
|
||||
if (!isDir(full)) continue
|
||||
if (entry.startsWith("@")) {
|
||||
for (const child of fs.readdirSync(full)) {
|
||||
if (isDir(path.join(full, child))) names.push(`${entry}/${child}`)
|
||||
}
|
||||
} else if (!entry.startsWith(".")) {
|
||||
names.push(entry)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// Packages plugins share with Quartz (gitLoader's getSharedExternals): one copy at runtime.
|
||||
const SINGLETONS = ["preact", "@jackyzha0/quartz", "vfile", "unified"]
|
||||
const SHARED_SCOPES = ["@quartz-community/", "@quartz-themes/"]
|
||||
|
||||
/**
|
||||
* Whether a dependency of a pinned plugin should come from Quartz's node_modules rather than
|
||||
* the plugin's own: a shared package (singletons, @quartz-community/*, Quartz's dependencies)
|
||||
* that Quartz has installed. Git plugins with a pre-built dist/ install no dependencies at
|
||||
* all, and resolve these from Quartz the same way.
|
||||
*/
|
||||
function sharedWithHost(dep, hostRoot) {
|
||||
let quartzDeps = []
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(hostRoot, "package.json"), "utf-8"))
|
||||
quartzDeps = Object.keys(pkg.dependencies ?? {})
|
||||
} catch {}
|
||||
const shared =
|
||||
SINGLETONS.includes(dep) ||
|
||||
SHARED_SCOPES.some((scope) => dep.startsWith(scope)) ||
|
||||
quartzDeps.includes(dep)
|
||||
return shared && fs.existsSync(path.join(hostRoot, "node_modules", ...dep.split("/")))
|
||||
}
|
||||
|
||||
function moveInto(from, to) {
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true })
|
||||
fs.rmSync(to, { recursive: true, force: true })
|
||||
fs.renameSync(from, to)
|
||||
}
|
||||
|
||||
/**
|
||||
* Install `name` at `version` (exact, a range or a tag; default `latest`) into
|
||||
* `<pluginsDir>/@scope/name`, with its production dependencies in its own node_modules and
|
||||
* without its peer dependencies (they resolve to Quartz's copies). With `integrity`, the
|
||||
* package npm downloads must match it. Returns the lock entry fields.
|
||||
*/
|
||||
export function installNpmPlugin(
|
||||
name,
|
||||
{ version = "latest", integrity, pluginsDir, verbose = false, run = npm } = {},
|
||||
) {
|
||||
const spec = assertNpmSpec(`${name}@${version}`)
|
||||
const quartzDir = path.dirname(pluginsDir)
|
||||
fs.mkdirSync(quartzDir, { recursive: true })
|
||||
const tmp = fs.mkdtempSync(path.join(quartzDir, ".npm-install-"))
|
||||
try {
|
||||
fs.writeFileSync(
|
||||
path.join(tmp, "package.json"),
|
||||
JSON.stringify({ name: "quartz-npm-plugin-install", private: true }) + "\n",
|
||||
)
|
||||
run(
|
||||
[
|
||||
"install",
|
||||
spec,
|
||||
"--save-exact",
|
||||
"--omit=dev",
|
||||
"--ignore-scripts",
|
||||
"--legacy-peer-deps",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
],
|
||||
{ cwd: tmp, stdio: verbose ? "inherit" : "pipe", timeout: NPM_INSTALL_TIMEOUT_MS },
|
||||
)
|
||||
|
||||
const lock = JSON.parse(fs.readFileSync(path.join(tmp, "package-lock.json"), "utf-8"))
|
||||
const locked = lock.packages?.[`node_modules/${name}`]
|
||||
if (!locked?.version) throw new Error(`npm did not install ${name}`)
|
||||
if (integrity && locked.integrity && locked.integrity !== integrity) {
|
||||
throw new Error(
|
||||
`${name}@${locked.version} from the registry does not match the integrity in quartz.lock.json ` +
|
||||
`(${locked.integrity} instead of ${integrity})`,
|
||||
)
|
||||
}
|
||||
|
||||
const modules = path.join(tmp, "node_modules")
|
||||
const target = npmPluginDir(name, pluginsDir)
|
||||
moveInto(path.join(modules, ...name.split("/")), target)
|
||||
|
||||
// what's left in node_modules are the plugin's dependencies: they go into its own
|
||||
// node_modules, except the ones it shares with Quartz (see sharedWithHost)
|
||||
const hostRoot = path.dirname(quartzDir)
|
||||
const deps = path.join(target, "node_modules")
|
||||
const keep = (dep, from, to) => {
|
||||
if (!sharedWithHost(dep, hostRoot)) moveInto(from, to)
|
||||
}
|
||||
for (const entry of fs.readdirSync(modules)) {
|
||||
if (entry === ".bin" || entry.startsWith(".") || entry === "@types") continue
|
||||
const from = path.join(modules, entry)
|
||||
if (entry.startsWith("@")) {
|
||||
for (const child of fs.readdirSync(from)) {
|
||||
keep(`${entry}/${child}`, path.join(from, child), path.join(deps, entry, child))
|
||||
}
|
||||
} else {
|
||||
keep(entry, from, path.join(deps, entry))
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
version: locked.version,
|
||||
...(locked.integrity && { integrity: locked.integrity }),
|
||||
...(locked.resolved && { resolved: locked.resolved }),
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a pinned npm plugin's directory (and its `@scope` directory when that is empty). */
|
||||
export function removeNpmPlugin(name, pluginsDir) {
|
||||
const dir = npmPluginDir(name, pluginsDir)
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
const scope = path.dirname(dir)
|
||||
if (scope !== pluginsDir) {
|
||||
try {
|
||||
if (fs.readdirSync(scope).length === 0) fs.rmdirSync(scope)
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock entry for an npm plugin just installed from `source`. Reinstalling the pinned version
|
||||
* (a fresh clone, `npm ci`, a CI runner) keeps `lockEntry` as it is, `installedAt` included, so
|
||||
* restoring plugins leaves quartz.lock.json unchanged, as it does for Git plugins.
|
||||
*/
|
||||
export function nextNpmLockEntry(lockEntry, source, result) {
|
||||
if (
|
||||
isNpmLockEntry(lockEntry) &&
|
||||
lockEntry.source === source &&
|
||||
lockEntry.version === result.version &&
|
||||
(!lockEntry.integrity || !result.integrity || lockEntry.integrity === result.integrity)
|
||||
) {
|
||||
return lockEntry
|
||||
}
|
||||
return { source, ...result, installedAt: new Date().toISOString() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Make sure the pinned npm plugin `name` is installed as `lockEntry` pins it (installed at the
|
||||
* locked version, else at `fallbackVersion`). Returns the lock entry fields when it installed
|
||||
* something, null when the right version was already there.
|
||||
*/
|
||||
export function ensureNpmPlugin(name, { lockEntry, fallbackVersion, pluginsDir, verbose } = {}) {
|
||||
const wanted = lockEntry?.version ?? fallbackVersion
|
||||
const installed = installedNpmPluginVersion(name, pluginsDir)
|
||||
if (installed && (!wanted || wanted === "latest" || installed === wanted)) return null
|
||||
return installNpmPlugin(name, {
|
||||
version: wanted ?? "latest",
|
||||
integrity: lockEntry?.version === wanted ? lockEntry?.integrity : undefined,
|
||||
pluginsDir,
|
||||
verbose,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
import test, { describe, beforeEach } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import fs from "fs"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import {
|
||||
ensureNpmPlugin,
|
||||
installedNpmPluginVersion,
|
||||
installNpmPlugin,
|
||||
isHostDependency,
|
||||
isNpmLockEntry,
|
||||
isPinnedNpmPluginInstalled,
|
||||
listPluginDirNames,
|
||||
nextNpmLockEntry,
|
||||
npmPackageName,
|
||||
npmPluginDir,
|
||||
readNpmLockEntry,
|
||||
removeNpmPlugin,
|
||||
} from "./npm-plugins.js"
|
||||
|
||||
const write = (file, content) => {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true })
|
||||
fs.writeFileSync(file, typeof content === "string" ? content : JSON.stringify(content))
|
||||
}
|
||||
|
||||
let root
|
||||
let pluginsDir
|
||||
beforeEach(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-npm-plugins-"))
|
||||
pluginsDir = path.join(root, ".quartz", "plugins")
|
||||
write(path.join(root, "package.json"), {
|
||||
name: "@jackyzha0/quartz",
|
||||
dependencies: { "@quartz-community/explorer": "^1", unified: "^11", "shared-dep": "^1" },
|
||||
devDependencies: { "@quartz-community/dev-only": "^1" },
|
||||
})
|
||||
// what Quartz has installed
|
||||
for (const dep of ["unified", "shared-dep", "@quartz-community/utils"]) {
|
||||
write(path.join(root, "node_modules", ...dep.split("/"), "package.json"), { name: dep })
|
||||
}
|
||||
})
|
||||
|
||||
describe("names and lock entries", () => {
|
||||
test("npmPackageName drops a version", () => {
|
||||
assert.strictEqual(npmPackageName("@me/plugin"), "@me/plugin")
|
||||
assert.strictEqual(npmPackageName("@me/plugin@1.2.3"), "@me/plugin")
|
||||
assert.strictEqual(npmPackageName("@me/plugin@^1"), "@me/plugin")
|
||||
})
|
||||
|
||||
test("an npm lock entry has a version and no commit", () => {
|
||||
assert.ok(isNpmLockEntry({ source: "@me/p", version: "1.0.0" }))
|
||||
assert.ok(!isNpmLockEntry({ source: "github:me/p", commit: "abc", version: "1.0.0" }))
|
||||
assert.ok(!isNpmLockEntry({ source: "./p", commit: "local" }))
|
||||
assert.ok(!isNpmLockEntry(undefined))
|
||||
})
|
||||
|
||||
test("readNpmLockEntry returns npm entries only", () => {
|
||||
const lockfile = path.join(root, "quartz.lock.json")
|
||||
write(lockfile, {
|
||||
version: "1.0.0",
|
||||
plugins: {
|
||||
"@me/p": { source: "@me/p", version: "2.0.0" },
|
||||
graph: { source: "github:me/graph", commit: "abc" },
|
||||
},
|
||||
})
|
||||
assert.strictEqual(readNpmLockEntry("@me/p", lockfile)?.version, "2.0.0")
|
||||
assert.strictEqual(readNpmLockEntry("graph", lockfile), undefined)
|
||||
assert.strictEqual(readNpmLockEntry("@me/p", path.join(root, "missing.json")), undefined)
|
||||
})
|
||||
|
||||
test("isHostDependency reads Quartz's package.json", () => {
|
||||
assert.ok(isHostDependency("@quartz-community/explorer", root))
|
||||
assert.ok(isHostDependency("@quartz-community/dev-only", root))
|
||||
assert.ok(!isHostDependency("@me/plugin", root))
|
||||
assert.ok(!isHostDependency("@me/plugin", path.join(root, "nowhere")))
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin directories", () => {
|
||||
test("pinned npm plugins live in @scope/name; listings include them", () => {
|
||||
write(path.join(pluginsDir, "graph", "package.json"), { name: "graph" })
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@me/plugin",
|
||||
version: "1.4.2",
|
||||
})
|
||||
fs.mkdirSync(path.join(pluginsDir, ".npm-install-x"), { recursive: true })
|
||||
write(path.join(pluginsDir, "index.ts"), "")
|
||||
assert.deepStrictEqual(listPluginDirNames(pluginsDir).sort(), ["@me/plugin", "graph"])
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), "1.4.2")
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/other", pluginsDir), null)
|
||||
})
|
||||
|
||||
test("a package with another name in the directory is not the plugin", () => {
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@someone/else",
|
||||
version: "1.0.0",
|
||||
})
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), null)
|
||||
})
|
||||
|
||||
test("package.json wins over a pinned copy", () => {
|
||||
write(path.join(npmPluginDir("@quartz-community/explorer", pluginsDir), "package.json"), {
|
||||
name: "@quartz-community/explorer",
|
||||
version: "1.0.0",
|
||||
})
|
||||
assert.ok(!isPinnedNpmPluginInstalled("@quartz-community/explorer", pluginsDir, root))
|
||||
})
|
||||
|
||||
test("removeNpmPlugin removes the scope directory once it is empty", () => {
|
||||
for (const name of ["@me/a", "@me/b"]) {
|
||||
write(path.join(npmPluginDir(name, pluginsDir), "package.json"), { name, version: "1.0.0" })
|
||||
}
|
||||
removeNpmPlugin("@me/a", pluginsDir)
|
||||
assert.ok(fs.existsSync(path.join(pluginsDir, "@me")))
|
||||
removeNpmPlugin("@me/b", pluginsDir)
|
||||
assert.ok(!fs.existsSync(path.join(pluginsDir, "@me")))
|
||||
removeNpmPlugin("@me/never-installed", pluginsDir)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* A stand-in for `npm install <spec>` in the temporary project: writes node_modules and
|
||||
* package-lock.json as npm would for @me/plugin with two dependencies, one of which Quartz has.
|
||||
*/
|
||||
function fakeNpm({ version = "1.4.2", integrity = "sha512-good" } = {}) {
|
||||
const calls = []
|
||||
const run = (args, { cwd }) => {
|
||||
calls.push({ args, cwd })
|
||||
const modules = path.join(cwd, "node_modules")
|
||||
write(path.join(modules, "@me", "plugin", "package.json"), { name: "@me/plugin", version })
|
||||
write(path.join(modules, "@me", "plugin", "dist", "index.js"), "export {}")
|
||||
write(path.join(modules, "own-dep", "package.json"), { name: "own-dep" })
|
||||
write(path.join(modules, "shared-dep", "package.json"), { name: "shared-dep" })
|
||||
write(path.join(modules, "@quartz-community", "utils", "package.json"), {
|
||||
name: "@quartz-community/utils",
|
||||
})
|
||||
write(path.join(modules, "@types", "node", "package.json"), { name: "@types/node" })
|
||||
write(path.join(modules, ".bin", "tool"), "")
|
||||
write(path.join(cwd, "package-lock.json"), {
|
||||
packages: {
|
||||
"node_modules/@me/plugin": {
|
||||
version,
|
||||
integrity,
|
||||
resolved: `https://registry.npmjs.org/@me/plugin/-/plugin-${version}.tgz`,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
return { run, calls }
|
||||
}
|
||||
|
||||
describe("installNpmPlugin", () => {
|
||||
test("installs into .quartz/plugins/@scope/name with its own dependencies", () => {
|
||||
const npm = fakeNpm()
|
||||
const result = installNpmPlugin("@me/plugin", { version: "1.4.2", pluginsDir, run: npm.run })
|
||||
assert.deepStrictEqual(result, {
|
||||
version: "1.4.2",
|
||||
integrity: "sha512-good",
|
||||
resolved: "https://registry.npmjs.org/@me/plugin/-/plugin-1.4.2.tgz",
|
||||
})
|
||||
const dir = npmPluginDir("@me/plugin", pluginsDir)
|
||||
assert.ok(fs.existsSync(path.join(dir, "dist", "index.js")))
|
||||
assert.ok(fs.existsSync(path.join(dir, "node_modules", "own-dep", "package.json")))
|
||||
// shared with Quartz: resolved from Quartz's node_modules, not a second copy
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "shared-dep")))
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "@quartz-community", "utils")))
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", "@types")))
|
||||
assert.ok(!fs.existsSync(path.join(dir, "node_modules", ".bin")))
|
||||
// the temporary project is gone, and nothing touched Quartz's package.json
|
||||
assert.deepStrictEqual(
|
||||
fs.readdirSync(path.join(root, ".quartz")).filter((n) => n.startsWith(".npm-install-")),
|
||||
[],
|
||||
)
|
||||
assert.ok(
|
||||
!JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf-8")).dependencies[
|
||||
"@me/plugin"
|
||||
],
|
||||
)
|
||||
|
||||
const [{ args }] = npm.calls
|
||||
assert.strictEqual(args[0], "install")
|
||||
assert.strictEqual(args[1], "@me/plugin@1.4.2")
|
||||
for (const flag of ["--omit=dev", "--ignore-scripts", "--legacy-peer-deps", "--save-exact"]) {
|
||||
assert.ok(args.includes(flag), flag)
|
||||
}
|
||||
})
|
||||
|
||||
test("a package that doesn't match the pinned integrity is refused and not installed", () => {
|
||||
const npm = fakeNpm({ integrity: "sha512-other" })
|
||||
assert.throws(
|
||||
() =>
|
||||
installNpmPlugin("@me/plugin", {
|
||||
version: "1.4.2",
|
||||
integrity: "sha512-good",
|
||||
pluginsDir,
|
||||
run: npm.run,
|
||||
}),
|
||||
/does not match the integrity in quartz\.lock\.json/,
|
||||
)
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), null)
|
||||
})
|
||||
|
||||
test("reinstalling replaces the previous version", () => {
|
||||
installNpmPlugin("@me/plugin", { version: "1.4.2", pluginsDir, run: fakeNpm().run })
|
||||
installNpmPlugin("@me/plugin", {
|
||||
version: "2.0.0",
|
||||
pluginsDir,
|
||||
run: fakeNpm({ version: "2.0.0" }).run,
|
||||
})
|
||||
assert.strictEqual(installedNpmPluginVersion("@me/plugin", pluginsDir), "2.0.0")
|
||||
})
|
||||
|
||||
test("an invalid name or version never reaches npm", () => {
|
||||
const npm = fakeNpm()
|
||||
assert.throws(() =>
|
||||
installNpmPlugin("@me/plugin", { version: "1$(id)", pluginsDir, run: npm.run }),
|
||||
)
|
||||
assert.throws(() => installNpmPlugin("--global", { pluginsDir, run: npm.run }))
|
||||
assert.strictEqual(npm.calls.length, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("ensureNpmPlugin", () => {
|
||||
test("does nothing when the pinned version is installed", () => {
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@me/plugin",
|
||||
version: "1.4.2",
|
||||
})
|
||||
assert.strictEqual(
|
||||
ensureNpmPlugin("@me/plugin", {
|
||||
lockEntry: { source: "@me/plugin", version: "1.4.2" },
|
||||
pluginsDir,
|
||||
}),
|
||||
null,
|
||||
)
|
||||
})
|
||||
|
||||
test("an installed plugin without a pin is left as it is", () => {
|
||||
write(path.join(npmPluginDir("@me/plugin", pluginsDir), "package.json"), {
|
||||
name: "@me/plugin",
|
||||
version: "1.0.0",
|
||||
})
|
||||
assert.strictEqual(ensureNpmPlugin("@me/plugin", { pluginsDir }), null)
|
||||
})
|
||||
})
|
||||
|
||||
describe("nextNpmLockEntry", () => {
|
||||
const pinned = {
|
||||
source: "@me/plugin",
|
||||
version: "1.4.2",
|
||||
integrity: "sha512-good",
|
||||
resolved: "https://registry.npmjs.org/@me/plugin/-/plugin-1.4.2.tgz",
|
||||
installedAt: "2026-01-01T00:00:00.000Z",
|
||||
}
|
||||
const result = { version: "1.4.2", integrity: "sha512-good", resolved: pinned.resolved }
|
||||
|
||||
test("reinstalling the pinned version keeps the lock entry, installedAt included", () => {
|
||||
assert.strictEqual(nextNpmLockEntry(pinned, "@me/plugin", result), pinned)
|
||||
})
|
||||
|
||||
test("a new version, source or package is a new entry", () => {
|
||||
const updated = nextNpmLockEntry(pinned, "@me/plugin", { ...result, version: "2.0.0" })
|
||||
assert.strictEqual(updated.version, "2.0.0")
|
||||
assert.notStrictEqual(updated.installedAt, pinned.installedAt)
|
||||
assert.notStrictEqual(nextNpmLockEntry(pinned, "@me/plugin@^1", result), pinned)
|
||||
assert.notStrictEqual(
|
||||
nextNpmLockEntry(pinned, "@me/plugin", { ...result, integrity: "sha512-other" }),
|
||||
pinned,
|
||||
)
|
||||
const added = nextNpmLockEntry(undefined, "@me/plugin", result)
|
||||
assert.deepStrictEqual(
|
||||
{ ...added, installedAt: undefined },
|
||||
{
|
||||
source: "@me/plugin",
|
||||
...result,
|
||||
installedAt: undefined,
|
||||
},
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,11 @@
|
||||
import { isHostDependency, npmPackageName, npmPluginDir } from "./npm-plugins.js"
|
||||
import { resolveLockfilePath } from "./lockfile-path.js"
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { execSync } from "child_process"
|
||||
import YAML, { isMap, isNode, isScalar, isSeq } from "yaml"
|
||||
|
||||
// Quartz's own folder; `quartz upgrade` merges this one. Plugin commands use getLockfilePath().
|
||||
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
|
||||
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
|
||||
const CONFIG_YAML_PATH = path.join(process.cwd(), "quartz.config.yaml")
|
||||
@@ -250,12 +253,16 @@ export function writePluginsJson(data) {
|
||||
// Edit the user's file in place; when it does not exist yet, start from the
|
||||
// file we read the config from (e.g. quartz.config.default.yaml) so its
|
||||
// comments carry over.
|
||||
// A config chosen with QUARTZ_CONFIG_PATH (`--config`) is the user's file: edited where it is
|
||||
// (it used to be read from there and written to ./quartz.config.yaml).
|
||||
const chosen = process.env.QUARTZ_CONFIG_PATH ? resolveConfigPath() : null
|
||||
const target = chosen && /\.ya?ml$/.test(chosen) ? chosen : CONFIG_YAML_PATH
|
||||
let baseRaw
|
||||
const basePath = fs.existsSync(CONFIG_YAML_PATH) ? CONFIG_YAML_PATH : resolveConfigPath()
|
||||
const basePath = fs.existsSync(target) ? target : resolveConfigPath()
|
||||
if (fs.existsSync(basePath) && (basePath.endsWith(".yaml") || basePath.endsWith(".yml"))) {
|
||||
baseRaw = fs.readFileSync(basePath, "utf-8")
|
||||
}
|
||||
writeDataToFile(CONFIG_YAML_PATH, rest, baseRaw)
|
||||
writeDataToFile(target, rest, baseRaw)
|
||||
}
|
||||
|
||||
function readDefaultPluginsJson() {
|
||||
@@ -263,10 +270,16 @@ function readDefaultPluginsJson() {
|
||||
return readFileAsData(defaultPath)
|
||||
}
|
||||
|
||||
/** quartz.lock.json of the config in use: next to it (see lockfile-path.js). */
|
||||
export function getLockfilePath() {
|
||||
return resolveLockfilePath(resolveConfigPath())
|
||||
}
|
||||
|
||||
export function readLockfile() {
|
||||
if (!fs.existsSync(LOCKFILE_PATH)) return null
|
||||
const lockfilePath = getLockfilePath()
|
||||
if (!fs.existsSync(lockfilePath)) return null
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(LOCKFILE_PATH, "utf-8"))
|
||||
return JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -280,7 +293,7 @@ export function writeLockfile(lockfile) {
|
||||
}
|
||||
lockfile = { ...lockfile, plugins: sorted }
|
||||
}
|
||||
fs.writeFileSync(LOCKFILE_PATH, JSON.stringify(lockfile, null, 2) + "\n")
|
||||
fs.writeFileSync(getLockfilePath(), JSON.stringify(lockfile, null, 2) + "\n")
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -374,8 +387,9 @@ export const SOURCE_FORMATS_HELP = [
|
||||
]
|
||||
|
||||
/**
|
||||
* Directory a configured plugin lives in: node_modules for npm packages,
|
||||
* .quartz/plugins/<name> for everything else. Returns null when unparseable.
|
||||
* Directory a configured plugin lives in: node_modules for npm packages package.json lists,
|
||||
* .quartz/plugins/@scope/<name> for other npm packages (pinned in quartz.lock.json, see
|
||||
* npm-plugins.js), .quartz/plugins/<name> for everything else. Returns null when unparseable.
|
||||
*/
|
||||
export function resolvePluginDir(source) {
|
||||
let parsed
|
||||
@@ -385,7 +399,8 @@ export function resolvePluginDir(source) {
|
||||
return null
|
||||
}
|
||||
if (parsed.npmPackage) {
|
||||
const pkgName = getSourceUrl(source)
|
||||
const pkgName = npmPackageName(getSourceUrl(source))
|
||||
if (!isHostDependency(pkgName)) return npmPluginDir(pkgName, PLUGINS_DIR)
|
||||
return path.join(process.cwd(), "node_modules", ...pkgName.split("/"))
|
||||
}
|
||||
return path.join(PLUGINS_DIR, parsed.name)
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
parseGitSource,
|
||||
getGitCommit,
|
||||
PLUGINS_DIR,
|
||||
LOCKFILE_PATH,
|
||||
getLockfilePath,
|
||||
isLocalSource,
|
||||
getSourceUrl,
|
||||
formatSource,
|
||||
@@ -56,6 +56,19 @@ import {
|
||||
npmAsync,
|
||||
} from "./subprocess.js"
|
||||
import { writePluginIndex } from "./plugin-index.js"
|
||||
import {
|
||||
installedNpmPluginVersion,
|
||||
installNpmPlugin,
|
||||
isHostDependency,
|
||||
isNpmLockEntry,
|
||||
nextNpmLockEntry,
|
||||
latestNpmVersion,
|
||||
latestNpmVersionAsync,
|
||||
listPluginDirNames,
|
||||
npmPackageName,
|
||||
npmPluginDir,
|
||||
removeNpmPlugin,
|
||||
} from "./npm-plugins.js"
|
||||
import {
|
||||
builtinKeyFor,
|
||||
builtinMessage,
|
||||
@@ -386,7 +399,12 @@ export function linkPeerPlugins(pluginDir) {
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
|
||||
const peers = pkg.peerDependencies ?? {}
|
||||
|
||||
const quartzRoot = path.resolve(pluginDir, "..", "..", "..")
|
||||
// .quartz/plugins/<name>, or .quartz/plugins/@scope/<name> for a pinned npm plugin
|
||||
const scoped = path.basename(path.dirname(pluginDir)).startsWith("@")
|
||||
const quartzRoot = path.resolve(
|
||||
pluginDir,
|
||||
...(scoped ? ["..", "..", "..", ".."] : ["..", "..", ".."]),
|
||||
)
|
||||
const hostNodeModules = path.join(quartzRoot, "node_modules")
|
||||
// a local plugin is a symlink; relative links made through it would dangle
|
||||
const realDir = fs.realpathSync(pluginDir)
|
||||
@@ -471,12 +489,8 @@ function canonicalSource(source) {
|
||||
function findPluginByPackageName(packageName) {
|
||||
if (!fs.existsSync(PLUGINS_DIR)) return null
|
||||
|
||||
const plugins = fs.readdirSync(PLUGINS_DIR).filter((entry) => {
|
||||
const entryPath = path.join(PLUGINS_DIR, entry)
|
||||
return fs.statSync(entryPath).isDirectory()
|
||||
})
|
||||
|
||||
for (const pluginDirName of plugins) {
|
||||
// `name` for Git and local plugins, `@scope/name` for pinned npm plugins
|
||||
for (const pluginDirName of listPluginDirNames(PLUGINS_DIR)) {
|
||||
const pkgPath = path.join(PLUGINS_DIR, pluginDirName, "package.json")
|
||||
if (!fs.existsSync(pkgPath)) continue
|
||||
try {
|
||||
@@ -497,12 +511,153 @@ async function regeneratePluginIndex() {
|
||||
if (builtinMessage(entry.source)) continue
|
||||
try {
|
||||
const parsed = parseGitSource(entry.source)
|
||||
if (parsed.npmPackage) npmPackages.push(parsed.name)
|
||||
// pinned npm plugins are directories in .quartz/plugins, which the index reads anyway
|
||||
if (parsed.npmPackage && isHostDependency(npmPackageName(parsed.name)))
|
||||
npmPackages.push(parsed.name)
|
||||
} catch {}
|
||||
}
|
||||
writePluginIndex({ pluginsDir: PLUGINS_DIR, npmPackages, verbose: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* The npm plugins `plugin install` takes care of: those package.json doesn't list are pinned in
|
||||
* quartz.lock.json and installed into .quartz/plugins/@scope/name (see npm-plugins.js); those it
|
||||
* lists stay with npm. Runs before the Git plugins and writes their lock entries itself; the Git
|
||||
* steps after it leave npm entries alone.
|
||||
*
|
||||
* - default: install each pinned plugin at its locked version (configured but unpinned ones get
|
||||
* a hint to run `install --from-config`)
|
||||
* - `fromConfig`: also pin and install configured ones without an entry (at the latest version),
|
||||
* and remove entries the config no longer has
|
||||
* - `latest`: move every pin to the version npm's `latest` tag points at
|
||||
*/
|
||||
async function syncNpmPlugins({ pluginsJson, names, fromConfig, latest, dryRun }) {
|
||||
const lockfile = readLockfile() ?? { version: "1.0.0", plugins: {} }
|
||||
lockfile.plugins ??= {}
|
||||
|
||||
const configured = new Map()
|
||||
for (const entry of pluginsJson?.plugins ?? []) {
|
||||
try {
|
||||
if (!parseGitSource(entry.source).npmPackage) continue
|
||||
const pkg = npmPackageName(getSourceUrl(entry.source))
|
||||
if (NPM_NAME_PATTERN.test(pkg)) configured.set(pkg, entry)
|
||||
} catch {}
|
||||
}
|
||||
const lockedNames = Object.entries(lockfile.plugins)
|
||||
.filter(([, entry]) => isNpmLockEntry(entry))
|
||||
.map(([name]) => name)
|
||||
const wanted = (pkg) =>
|
||||
!names?.length || names.some((n) => n === pkg || n === shortPluginName(pkg))
|
||||
const all = [...new Set([...configured.keys(), ...lockedNames])].filter(wanted)
|
||||
|
||||
let changed = false
|
||||
let installedAny = false
|
||||
|
||||
// package.json wins: an entry left from when the plugin was pinned goes
|
||||
for (const pkg of all.filter((p) => isHostDependency(p))) {
|
||||
if (!isNpmLockEntry(lockfile.plugins[pkg])) continue
|
||||
console.log(styleText("gray", `${pkg} is in package.json, which versions it: removing its pin`))
|
||||
if (dryRun) continue
|
||||
delete lockfile.plugins[pkg]
|
||||
removeNpmPlugin(pkg, PLUGINS_DIR)
|
||||
changed = true
|
||||
}
|
||||
|
||||
const unpinned = []
|
||||
const rows = []
|
||||
for (const pkg of all.filter((p) => !isHostDependency(p))) {
|
||||
const entry = configured.get(pkg)
|
||||
const lockEntry = isNpmLockEntry(lockfile.plugins[pkg]) ? lockfile.plugins[pkg] : undefined
|
||||
|
||||
if (!entry) {
|
||||
// pinned, but no longer configured
|
||||
if (!fromConfig) continue
|
||||
console.log(styleText("yellow", `${pkg} — pinned but not in the config: removing it`))
|
||||
if (dryRun) continue
|
||||
delete lockfile.plugins[pkg]
|
||||
removeNpmPlugin(pkg, PLUGINS_DIR)
|
||||
changed = true
|
||||
installedAny = true
|
||||
continue
|
||||
}
|
||||
// like Git plugins: a disabled plugin isn't installed until it is pinned
|
||||
if (!lockEntry && !entry.enabled) continue
|
||||
if (!lockEntry && !fromConfig && !latest) {
|
||||
unpinned.push(pkg)
|
||||
continue
|
||||
}
|
||||
|
||||
const installedVersion = installedNpmPluginVersion(pkg, PLUGINS_DIR)
|
||||
let version = lockEntry?.version
|
||||
if (latest || !version) {
|
||||
try {
|
||||
version = latestNpmVersion(pkg)
|
||||
} catch (err) {
|
||||
console.log(styleText("red", `✗ ${pkg}: could not look up its latest version on npm`))
|
||||
console.log(styleText("gray", ` ${describeCommandError(err)}`))
|
||||
markFailed()
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
rows.push({ pkg, installed: installedVersion ?? "—", target: version })
|
||||
continue
|
||||
}
|
||||
// `restore` (clean) also leaves a plugin that is installed at its pinned version alone
|
||||
if (installedVersion === version && lockEntry?.version === version) continue
|
||||
|
||||
try {
|
||||
console.log(styleText("cyan", `→ Installing ${pkg}@${version} from npm...`))
|
||||
const result = installNpmPlugin(pkg, {
|
||||
version,
|
||||
integrity: lockEntry?.version === version ? lockEntry.integrity : undefined,
|
||||
pluginsDir: PLUGINS_DIR,
|
||||
})
|
||||
linkPeerPlugins(npmPluginDir(pkg, PLUGINS_DIR))
|
||||
const next = nextNpmLockEntry(lockEntry, entry.source, result)
|
||||
if (next !== lockEntry) {
|
||||
lockfile.plugins[pkg] = next
|
||||
changed = true
|
||||
}
|
||||
installedAny = true
|
||||
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
|
||||
} catch (err) {
|
||||
console.log(styleText("red", `✗ Failed to install ${pkg} from npm`))
|
||||
console.log(styleText("gray", ` ${describeCommandError(err)}`))
|
||||
markFailed()
|
||||
}
|
||||
}
|
||||
|
||||
if (rows.length > 0) {
|
||||
console.log(styleText("bold", latest ? "npm plugins (latest):" : "npm plugins to install:"))
|
||||
const width = Math.max(...rows.map((row) => row.pkg.length)) + 2
|
||||
for (const { pkg, installed, target } of rows) {
|
||||
const status =
|
||||
installed === target
|
||||
? styleText("green", "up to date")
|
||||
: styleText("yellow", `${installed} → ${target}`)
|
||||
console.log(` ${pkg.padEnd(width)}${status}`)
|
||||
}
|
||||
console.log()
|
||||
}
|
||||
if (unpinned.length > 0) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`⚠ ${unpinned.length} npm plugin(s) in the config are not pinned in quartz.lock.json: ${unpinned.join(", ")}`,
|
||||
),
|
||||
)
|
||||
console.log(
|
||||
styleText("gray", " Run 'npx quartz plugin install --from-config' to install and pin them."),
|
||||
)
|
||||
}
|
||||
|
||||
if (changed && !dryRun) writeLockfile(lockfile)
|
||||
if (installedAny && !dryRun) await regeneratePluginIndex()
|
||||
return { installedAny }
|
||||
}
|
||||
|
||||
export async function handlePluginInstallUnified({
|
||||
names,
|
||||
fromConfig = false,
|
||||
@@ -528,14 +683,34 @@ export async function handlePluginInstallUnified({
|
||||
...rawPluginsJson,
|
||||
plugins: (rawPluginsJson.plugins ?? []).filter((entry) => !builtinMessage(entry.source)),
|
||||
}
|
||||
// npm plugins package.json doesn't list are pinned and installed first; without a lockfile
|
||||
// they are pinned from the config, as Git plugins are below
|
||||
const hadLockfile = readLockfile() !== null
|
||||
await syncNpmPlugins({
|
||||
pluginsJson,
|
||||
names,
|
||||
fromConfig: fromConfig || !hadLockfile,
|
||||
latest,
|
||||
dryRun,
|
||||
})
|
||||
|
||||
// the steps below handle Git and local plugins; npm entries are written back as they are
|
||||
let lockfile = readLockfile()
|
||||
const npmLockEntries = Object.fromEntries(
|
||||
Object.entries(lockfile?.plugins ?? {}).filter(([, entry]) => isNpmLockEntry(entry)),
|
||||
)
|
||||
const withNpmEntries = (lf) => ({ ...lf, plugins: { ...npmLockEntries, ...lf.plugins } })
|
||||
if (lockfile) {
|
||||
lockfile = {
|
||||
...lockfile,
|
||||
plugins: Object.fromEntries(
|
||||
Object.entries(lockfile.plugins ?? {}).filter(([name]) => !builtinMessage(name)),
|
||||
Object.entries(lockfile.plugins ?? {}).filter(
|
||||
([name, entry]) => !builtinMessage(name) && !isNpmLockEntry(entry),
|
||||
),
|
||||
),
|
||||
}
|
||||
// a lockfile the npm step just created holds no Git pins: install those from the config
|
||||
if (!hadLockfile && Object.keys(lockfile.plugins).length === 0) lockfile = null
|
||||
}
|
||||
|
||||
if (!fromConfig && !lockfile) {
|
||||
@@ -547,12 +722,7 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
})
|
||||
if (gitEntries.length === 0 && findMissingNpmPlugins(pluginsJson).length === 0) {
|
||||
console.log(
|
||||
styleText(
|
||||
"green",
|
||||
"✓ No Git or local plugins to install (plugins from npm are installed by 'npm install' / 'npm ci')",
|
||||
),
|
||||
)
|
||||
console.log(styleText("green", "✓ No Git or local plugins to install"))
|
||||
return
|
||||
}
|
||||
if (dryRun && latest) {
|
||||
@@ -992,7 +1162,7 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
|
||||
if (lockfileChanged) {
|
||||
writeLockfile(lockfile)
|
||||
writeLockfile(withNpmEntries(lockfile))
|
||||
console.log()
|
||||
if (failed === 0) {
|
||||
console.log(styleText("green", `✓ Resolved ${installed.length} plugin(s)`))
|
||||
@@ -1160,6 +1330,13 @@ export async function handlePluginInstallUnified({
|
||||
const pluginsToUpdate = nameFilter ? Array.from(nameFilter) : Object.keys(lockfile.plugins)
|
||||
const updatedPlugins = []
|
||||
let lockfileChanged = false
|
||||
// Disabled in the config: the build never loads them, so failing to update one is a warning,
|
||||
// not a failed update (an old entry whose repository changed layout failed every update).
|
||||
const disabledNames = new Set(
|
||||
(pluginsJson?.plugins ?? [])
|
||||
.filter((entry) => entry.enabled === false)
|
||||
.map((entry) => extractPluginName(entry.source)),
|
||||
)
|
||||
|
||||
// Phase 1: Validate and categorize plugins (fast, sequential)
|
||||
const validPlugins = []
|
||||
@@ -1244,6 +1421,16 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (disabledNames.has(name)) {
|
||||
console.log(
|
||||
styleText(
|
||||
"yellow",
|
||||
`⚠ Could not update ${name} (disabled, so the build does not load it): ${describeCommandError(error)}\n` +
|
||||
` Remove it with \`npx quartz plugin remove ${name}\` or fix its source.`,
|
||||
),
|
||||
)
|
||||
return
|
||||
}
|
||||
console.log(
|
||||
styleText("red", `✗ Failed to update ${name}: ${describeCommandError(error)}`),
|
||||
)
|
||||
@@ -1271,7 +1458,7 @@ export async function handlePluginInstallUnified({
|
||||
}
|
||||
|
||||
if (lockfileChanged) {
|
||||
writeLockfile(lockfile)
|
||||
writeLockfile(withNpmEntries(lockfile))
|
||||
console.log()
|
||||
console.log(styleText("gray", "Updated quartz.lock.json"))
|
||||
}
|
||||
@@ -1483,7 +1670,11 @@ export async function handlePluginInstallUnified({
|
||||
|
||||
const NPM_NAME_PATTERN = /^@[a-z0-9-~][a-z0-9-._~]*\/[a-z0-9-~][a-z0-9-._~]*$/
|
||||
|
||||
/** Enabled npm-sourced plugins whose package is not present in node_modules. */
|
||||
/**
|
||||
* Enabled npm-sourced plugins in package.json whose package is not present in node_modules
|
||||
* (`npm install` installs them). Plugins package.json doesn't list are pinned in
|
||||
* quartz.lock.json instead, see syncNpmPlugins.
|
||||
*/
|
||||
function findMissingNpmPlugins(pluginsJson) {
|
||||
const missing = []
|
||||
for (const entry of pluginsJson?.plugins ?? []) {
|
||||
@@ -1492,6 +1683,7 @@ function findMissingNpmPlugins(pluginsJson) {
|
||||
if (!parseGitSource(entry.source).npmPackage) continue
|
||||
const pkg = getSourceUrl(entry.source)
|
||||
if (!NPM_NAME_PATTERN.test(pkg)) continue
|
||||
if (!isHostDependency(npmPackageName(pkg))) continue
|
||||
const dir = resolvePluginDir(entry.source)
|
||||
if (dir && !fs.existsSync(path.join(dir, "package.json"))) missing.push(pkg)
|
||||
} catch {}
|
||||
@@ -1587,11 +1779,46 @@ export async function handlePluginAdd(
|
||||
)
|
||||
continue
|
||||
}
|
||||
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
|
||||
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
|
||||
const configSource = nameOverride ? { repo: parsed.name, name: nameOverride } : parsed.name
|
||||
const pluginDir = path.join(process.cwd(), "node_modules", ...parsed.name.split("/"))
|
||||
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
|
||||
const pkg = npmPackageName(parsed.name)
|
||||
if (isHostDependency(pkg)) {
|
||||
// in package.json already (a default plugin, or one installed with npm): npm's
|
||||
console.log(styleText("cyan", `→ Installing ${name} from npm (package.json)...`))
|
||||
npm(["install", assertNpmSpec(parsed.name)], { cwd: process.cwd(), stdio: "inherit" })
|
||||
const pluginDir = path.join(process.cwd(), "node_modules", ...pkg.split("/"))
|
||||
addedPlugins.push({ name, pluginDir, source: parsed.name, configSource, npm: true })
|
||||
continue
|
||||
}
|
||||
// pinned in quartz.lock.json and installed into .quartz/plugins/@scope/name, so Quartz's
|
||||
// package.json stays as Quartz ships it (see npm-plugins.js)
|
||||
console.log(styleText("cyan", `→ Installing ${name} from npm...`))
|
||||
const requested = parsed.name.slice(pkg.length + 1) || "latest"
|
||||
let result
|
||||
try {
|
||||
result = installNpmPlugin(pkg, { version: requested, pluginsDir: PLUGINS_DIR })
|
||||
} catch (err) {
|
||||
console.log(styleText("red", `✗ Failed to install ${pkg} from npm`))
|
||||
console.log(styleText("gray", ` ${describeCommandError(err)}`))
|
||||
hadFailure = true
|
||||
continue
|
||||
}
|
||||
const pluginDir = npmPluginDir(pkg, PLUGINS_DIR)
|
||||
linkPeerPlugins(pluginDir)
|
||||
lockfile.plugins[pkg] = {
|
||||
source: configSource,
|
||||
...result,
|
||||
installedAt: new Date().toISOString(),
|
||||
}
|
||||
lockfileChanged = true
|
||||
console.log(styleText("green", `✓ Installed ${pkg}@${result.version}`))
|
||||
addedPlugins.push({
|
||||
name,
|
||||
pluginDir,
|
||||
source: parsed.name,
|
||||
configSource,
|
||||
npm: true,
|
||||
skipBuild: true,
|
||||
})
|
||||
continue
|
||||
}
|
||||
const name = nameOverride ?? parsed.name
|
||||
@@ -1895,11 +2122,17 @@ export async function handlePluginRemove(names) {
|
||||
try {
|
||||
const parsed = parseGitSource(configEntry.source)
|
||||
isNpm = Boolean(parsed.npmPackage)
|
||||
if (!isNpm && !lockfile.plugins[lockKey]) lockKey = parsed.name
|
||||
if (isNpm) lockKey = npmPackageName(getSourceUrl(configEntry.source))
|
||||
else if (!lockfile.plugins[lockKey]) lockKey = parsed.name
|
||||
} catch {}
|
||||
} else if (isNpmLockEntry(lockfile.plugins[lockKey])) {
|
||||
isNpm = true
|
||||
}
|
||||
const pluginDir = path.join(PLUGINS_DIR, lockKey)
|
||||
const installed = !isNpm && (Boolean(lockfile.plugins[lockKey]) || fs.existsSync(pluginDir))
|
||||
// an npm plugin package.json doesn't list is pinned and installed like a Git plugin
|
||||
const pinnedNpm = isNpm && !isHostDependency(lockKey)
|
||||
const pluginDir = path.join(PLUGINS_DIR, ...lockKey.split("/"))
|
||||
const installed =
|
||||
(!isNpm || pinnedNpm) && (Boolean(lockfile.plugins[lockKey]) || fs.existsSync(pluginDir))
|
||||
|
||||
if (!configEntry && !installed) {
|
||||
const candidates = [
|
||||
@@ -1925,7 +2158,10 @@ export async function handlePluginRemove(names) {
|
||||
console.log(styleText("cyan", `→ Removing ${displayName}...`))
|
||||
|
||||
if (installed) {
|
||||
if (fs.existsSync(pluginDir) || fs.lstatSync(pluginDir, { throwIfNoEntry: false })) {
|
||||
if (pinnedNpm) {
|
||||
removeNpmPlugin(lockKey, PLUGINS_DIR)
|
||||
removedFiles = true
|
||||
} else if (fs.existsSync(pluginDir) || fs.lstatSync(pluginDir, { throwIfNoEntry: false })) {
|
||||
fs.rmSync(pluginDir, { recursive: true, force: true })
|
||||
removedFiles = true
|
||||
}
|
||||
@@ -1940,7 +2176,7 @@ export async function handlePluginRemove(names) {
|
||||
removedSources.push(configEntry.source)
|
||||
}
|
||||
console.log(styleText("green", `✓ Removed ${displayName}`))
|
||||
if (isNpm) {
|
||||
if (isNpm && !pinnedNpm && configEntry) {
|
||||
console.log(
|
||||
styleText(
|
||||
"gray",
|
||||
@@ -2212,6 +2448,18 @@ function collectUntrackedEntries(pluginsJson, lockfile) {
|
||||
continue
|
||||
}
|
||||
if (parsed.npmPackage) {
|
||||
const pkgName = npmPackageName(getSourceUrl(entry.source))
|
||||
if (!isHostDependency(pkgName)) {
|
||||
// pinned in quartz.lock.json like Git plugins; missing when it has no entry yet
|
||||
if (!isNpmLockEntry(lockfile?.plugins?.[pkgName])) {
|
||||
missing.push({
|
||||
name: extractPluginName(entry.source),
|
||||
source: formatSource(entry.source),
|
||||
enabled: Boolean(entry.enabled),
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
const pkg = readEntryPackageJson(entry.source)
|
||||
npm.push({
|
||||
name: extractPluginName(entry.source),
|
||||
@@ -2260,18 +2508,43 @@ export async function handlePluginList() {
|
||||
: styleText("gray", "disabled")
|
||||
|
||||
if (lockEntries.length > 0) {
|
||||
console.log(styleText("bold", "Git / local plugins (quartz.lock.json):"))
|
||||
console.log(styleText("bold", "Pinned plugins (quartz.lock.json):"))
|
||||
console.log()
|
||||
}
|
||||
|
||||
for (const [name, entry] of lockEntries) {
|
||||
const pluginDir = path.join(PLUGINS_DIR, name)
|
||||
const pluginDir = path.join(PLUGINS_DIR, ...name.split("/"))
|
||||
const exists = fs.existsSync(pluginDir)
|
||||
const overriddenName = nameOverrides.get(name)
|
||||
const displayLabel = overriddenName
|
||||
? `${overriddenName} ${styleText("gray", `(dir: ${name})`)}`
|
||||
: name
|
||||
|
||||
if (isNpmLockEntry(entry)) {
|
||||
const installedVersion = installedNpmPluginVersion(name, PLUGINS_DIR)
|
||||
const status = !installedVersion
|
||||
? styleText("red", "✗")
|
||||
: installedVersion === entry.version
|
||||
? styleText("green", "✓")
|
||||
: styleText("yellow", "⚡")
|
||||
console.log(
|
||||
` ${status} ${styleText("bold", displayLabel)} ${enabledLabel(overriddenName ?? name)}`,
|
||||
)
|
||||
console.log(` Source: ${formatSource(entry.source)} (npm)`)
|
||||
console.log(` Version: ${entry.version}`)
|
||||
if (installedVersion && installedVersion !== entry.version) {
|
||||
console.log(
|
||||
` Current: ${installedVersion} (differs from lockfile — run 'npx quartz plugin install ${name}')`,
|
||||
)
|
||||
}
|
||||
if (!installedVersion) console.log(` Not on disk — run 'npx quartz plugin install'`)
|
||||
if (entry.installedAt) {
|
||||
console.log(` Installed: ${new Date(entry.installedAt).toLocaleDateString()}`)
|
||||
}
|
||||
console.log()
|
||||
continue
|
||||
}
|
||||
|
||||
if (entry.commit === "local") {
|
||||
const isLinked = exists && fs.lstatSync(pluginDir).isSymbolicLink()
|
||||
const status = isLinked ? styleText("green", "✓") : styleText("red", "✗")
|
||||
@@ -2371,6 +2644,19 @@ export async function handlePluginStatus() {
|
||||
)
|
||||
|
||||
const rows = Object.entries(lockfile.plugins).map(([name, entry]) => {
|
||||
if (isNpmLockEntry(entry)) {
|
||||
const installedVersion = installedNpmPluginVersion(name, PLUGINS_DIR)
|
||||
return {
|
||||
name,
|
||||
entry,
|
||||
npmPinned: true,
|
||||
exists: installedVersion !== null,
|
||||
displayName: nameOverrides.get(name) ?? name,
|
||||
sourceLabel: `${formatSource(entry.source)} (npm)`,
|
||||
commitLabel: `v${entry.version}`,
|
||||
enabled: enabledByName.get(extractPluginName(entry.source)) ?? false,
|
||||
}
|
||||
}
|
||||
const pluginDir = path.join(PLUGINS_DIR, name)
|
||||
const exists = fs.existsSync(pluginDir)
|
||||
const displayName = nameOverrides.get(name) ?? name
|
||||
@@ -2465,6 +2751,21 @@ export async function handlePluginStatus() {
|
||||
})
|
||||
}
|
||||
|
||||
if (row.npmPinned) {
|
||||
return latestNpmVersionAsync(row.name)
|
||||
.then((latestVersion) => {
|
||||
const status = latestVersion === row.entry.version ? "up_to_date" : "update_available"
|
||||
const display = updateDisplay(status)
|
||||
updateLine(index, display.label, display.text)
|
||||
return { index, status, name: row.displayName }
|
||||
})
|
||||
.catch(() => {
|
||||
const display = updateDisplay("failed")
|
||||
updateLine(index, display.label, display.text)
|
||||
return { index, status: "failed", name: row.displayName }
|
||||
})
|
||||
}
|
||||
|
||||
return lsRemote(row.entry)
|
||||
.then(({ stdout }) => {
|
||||
const latestCommit = stdout.split("\t")[0].trim()
|
||||
@@ -2502,13 +2803,13 @@ export async function handlePluginStatus() {
|
||||
console.log(
|
||||
styleText(
|
||||
"gray",
|
||||
"\nnpm plugins are versioned by package.json — update them with 'npx quartz upgrade' or 'npm update'.",
|
||||
"\nnpm plugins in package.json are versioned there — update them with 'npx quartz upgrade' or 'npm update'.",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
if (updatesAvailable.length === 0 && failedChecks.length === 0) {
|
||||
console.log(styleText("green", "\n✓ All Git plugins up to date"))
|
||||
console.log(styleText("green", "\n✓ All pinned plugins up to date"))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -2643,7 +2944,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
const plugins = effective.plugins.filter((entry) => !absorbed.has(entry))
|
||||
|
||||
const lockfile = readLockfile()
|
||||
if (fs.existsSync(LOCKFILE_PATH) && !lockfile) {
|
||||
if (fs.existsSync(getLockfilePath()) && !lockfile) {
|
||||
report(
|
||||
"error",
|
||||
"quartz.lock.json",
|
||||
@@ -2717,14 +3018,55 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
|
||||
const pluginDir = resolvePluginDir(entry.source)
|
||||
if (parsed.npmPackage) {
|
||||
if (!fs.existsSync(path.join(pluginDir, "package.json"))) {
|
||||
report(
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
"npm package is not installed",
|
||||
`Run 'npm install' (or 'npm install ${parsed.name}' if it is not in package.json).`,
|
||||
)
|
||||
return
|
||||
const pkgName = npmPackageName(getSourceUrl(entry.source))
|
||||
const pin = lockfile?.plugins?.[pkgName]
|
||||
if (isHostDependency(pkgName)) {
|
||||
if (isNpmLockEntry(pin)) {
|
||||
report(
|
||||
"warning",
|
||||
label,
|
||||
"is in package.json and also pinned in quartz.lock.json; package.json versions it",
|
||||
`Run 'npx quartz plugin install ${pkgName}' to remove the unused pin.`,
|
||||
)
|
||||
}
|
||||
if (!fs.existsSync(path.join(pluginDir, "package.json"))) {
|
||||
report(
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
"npm package is not installed",
|
||||
"Run 'npm install'.",
|
||||
)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// pinned in quartz.lock.json, installed into .quartz/plugins/@scope/name
|
||||
const installedVersion = installedNpmPluginVersion(pkgName, PLUGINS_DIR)
|
||||
if (!isNpmLockEntry(pin)) {
|
||||
if (enabled) {
|
||||
report(
|
||||
"warning",
|
||||
label,
|
||||
"not pinned in quartz.lock.json — the build installs the latest version",
|
||||
"Run 'npx quartz plugin install --from-config' and commit quartz.lock.json.",
|
||||
)
|
||||
}
|
||||
if (!installedVersion) return
|
||||
} else if (!installedVersion) {
|
||||
report(
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
`npm package is not installed (quartz.lock.json pins ${pin.version})`,
|
||||
"Run 'npx quartz plugin install'.",
|
||||
)
|
||||
return
|
||||
} else if (installedVersion !== pin.version) {
|
||||
report(
|
||||
"warning",
|
||||
label,
|
||||
`${installedVersion} is installed but quartz.lock.json pins ${pin.version}`,
|
||||
`Run 'npx quartz plugin install ${pkgName}' to install the pinned version.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
gitPluginCount++
|
||||
@@ -2790,7 +3132,7 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
enabled ? "error" : "info",
|
||||
label,
|
||||
"has no built entry point (dist/ missing)",
|
||||
parsed.npmPackage
|
||||
parsed.npmPackage && isHostDependency(npmPackageName(getSourceUrl(entry.source)))
|
||||
? "Reinstall it with 'npm install'."
|
||||
: `Run 'npx quartz plugin install ${parsed.name}' to build it.`,
|
||||
)
|
||||
@@ -2868,7 +3210,11 @@ export async function handlePluginDoctor({ verbose = false, fix = false } = {})
|
||||
const configured = new Set(
|
||||
plugins.flatMap((e) => {
|
||||
try {
|
||||
return [parseGitSource(e.source).name]
|
||||
const parsed = parseGitSource(e.source)
|
||||
// npm pins are keyed by package name, also when the config renames the plugin
|
||||
return parsed.npmPackage
|
||||
? [parsed.name, npmPackageName(getSourceUrl(e.source))]
|
||||
: [parsed.name]
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
@@ -2932,6 +3278,13 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
|
||||
const configuredNames = new Set(
|
||||
(pluginsJson?.plugins ?? []).map((entry) => extractPluginName(entry.source)),
|
||||
)
|
||||
// npm pins are keyed by package name, also when the config gives the plugin another name
|
||||
for (const entry of pluginsJson?.plugins ?? []) {
|
||||
try {
|
||||
if (parseGitSource(entry.source).npmPackage)
|
||||
configuredNames.add(npmPackageName(getSourceUrl(entry.source)))
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const orphans = Object.keys(lockfile.plugins).filter((name) => !configuredNames.has(name))
|
||||
|
||||
@@ -2957,7 +3310,9 @@ export async function handlePluginPrune({ dryRun = false } = {}) {
|
||||
|
||||
console.log(styleText("cyan", `→ Removing ${name}...`))
|
||||
|
||||
if (fs.existsSync(pluginDir)) {
|
||||
if (isNpmLockEntry(lockfile.plugins[name])) {
|
||||
removeNpmPlugin(name, PLUGINS_DIR)
|
||||
} else if (fs.existsSync(pluginDir)) {
|
||||
fs.rmSync(pluginDir, { recursive: true })
|
||||
}
|
||||
|
||||
|
||||
@@ -229,7 +229,15 @@ describe("plugin commands with an extending config", () => {
|
||||
const site = () => {
|
||||
const dir = path.join(root, "site")
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.0" }`)
|
||||
// the default plugins are Quartz's dependencies, as in Quartz's own package.json
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "package.json"),
|
||||
JSON.stringify({
|
||||
name: "site",
|
||||
version: "5.3.0",
|
||||
dependencies: { "@quartz-community/graph": "^1", "@quartz-community/comments": "^1" },
|
||||
}),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.default.yaml"),
|
||||
[
|
||||
@@ -294,3 +302,122 @@ describe("plugin commands with an extending config", () => {
|
||||
assert.doesNotMatch(read(dir), /comments/)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin install --latest with a plugin that can't be updated", () => {
|
||||
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
|
||||
// A Git plugin whose repository no longer has the configured subdirectory (an old
|
||||
// quartz-themes entry: the repository moved its plugin out of `plugin/`).
|
||||
const site = (enabled) => {
|
||||
const repo = path.join(root, "repo")
|
||||
fs.mkdirSync(repo, { recursive: true })
|
||||
fs.writeFileSync(path.join(repo, "README.md"), "no plugin/ here\n")
|
||||
const git = (args) => execSync(`git ${args}`, { cwd: repo, stdio: "ignore", timeout: 30_000 })
|
||||
git("init -q -b main")
|
||||
git("-c user.name=t -c user.email=t@t add .")
|
||||
git("-c user.name=t -c user.email=t@t commit -q -m init")
|
||||
const url = pathToFileURL(repo).href
|
||||
const dir = path.join(root, "site")
|
||||
fs.mkdirSync(path.join(dir, ".quartz", "plugins", "old-theme"), { recursive: true })
|
||||
fs.writeFileSync(path.join(dir, "package.json"), `{ "name": "site", "version": "5.3.1" }`)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.config.yaml"),
|
||||
YAML.stringify({
|
||||
configuration: { pageTitle: "t" },
|
||||
plugins: [{ source: { name: "old-theme", repo: url, subdir: "plugin" }, enabled }],
|
||||
}),
|
||||
)
|
||||
fs.writeFileSync(
|
||||
path.join(dir, "quartz.lock.json"),
|
||||
JSON.stringify({
|
||||
version: "1.0.0",
|
||||
plugins: {
|
||||
"old-theme": {
|
||||
source: url,
|
||||
resolved: url,
|
||||
subdir: "plugin",
|
||||
commit: "0000000000000000000000000000000000000000",
|
||||
installedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
)
|
||||
return dir
|
||||
}
|
||||
const run = (dir) => {
|
||||
const result = spawnSync(process.execPath, [cli, "plugin", "install", "--latest"], {
|
||||
cwd: dir,
|
||||
encoding: "utf-8",
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
|
||||
})
|
||||
return { output: result.stdout + result.stderr, status: result.status }
|
||||
}
|
||||
|
||||
test("a disabled plugin only warns: the build doesn't load it", () => {
|
||||
const { output, status } = run(site(false))
|
||||
assert.match(output, /Could not update old-theme \(disabled/)
|
||||
assert.match(output, /npx quartz plugin remove old-theme/)
|
||||
assert.strictEqual(status, 0)
|
||||
})
|
||||
|
||||
test("an enabled plugin fails the update", () => {
|
||||
const { output, status } = run(site(true))
|
||||
assert.match(output, /Failed to update old-theme/)
|
||||
assert.strictEqual(status, 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin commands with --config elsewhere", () => {
|
||||
const cli = path.resolve(import.meta.dirname, "..", "bootstrap-cli.mjs")
|
||||
const run = (cwd, args) =>
|
||||
spawnSync(process.execPath, [cli, ...args], {
|
||||
cwd,
|
||||
encoding: "utf-8",
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, QUARTZ_CONFIG_PATH: "" },
|
||||
})
|
||||
|
||||
test("-C reads and writes that config and the quartz.lock.json next to it", () => {
|
||||
const quartz = path.join(root, "quartz")
|
||||
fs.mkdirSync(quartz, { recursive: true })
|
||||
fs.writeFileSync(path.join(quartz, "package.json"), `{ "name": "q", "version": "5.3.0" }`)
|
||||
fs.writeFileSync(path.join(quartz, "quartz.config.default.yaml"), "plugins: []\n")
|
||||
// a site repository outside Quartz: content, config and lockfile only
|
||||
const site = path.join(root, "site")
|
||||
fs.mkdirSync(site, { recursive: true })
|
||||
fs.writeFileSync(path.join(site, "quartz.config.yaml"), "extends: default\n")
|
||||
const plugin = path.join(root, "my-plugin")
|
||||
fs.mkdirSync(plugin, { recursive: true })
|
||||
fs.writeFileSync(
|
||||
path.join(plugin, "package.json"),
|
||||
`{ "name": "my-plugin", "version": "1.0.0" }`,
|
||||
)
|
||||
// pre-built, so `add` doesn't build it
|
||||
fs.mkdirSync(path.join(plugin, "dist"))
|
||||
fs.writeFileSync(path.join(plugin, "dist", "index.js"), "export {}\n")
|
||||
fs.writeFileSync(path.join(plugin, "dist", "index.d.ts"), "export {}\n")
|
||||
|
||||
const result = run(quartz, [
|
||||
"plugin",
|
||||
"add",
|
||||
plugin,
|
||||
"-C",
|
||||
path.join(site, "quartz.config.yaml"),
|
||||
])
|
||||
assert.strictEqual(result.status, 0, result.stdout + result.stderr)
|
||||
const lock = JSON.parse(fs.readFileSync(path.join(site, "quartz.lock.json"), "utf-8"))
|
||||
assert.strictEqual(lock.plugins["my-plugin"]?.commit, "local")
|
||||
assert.ok(!fs.existsSync(path.join(quartz, "quartz.lock.json")))
|
||||
assert.match(fs.readFileSync(path.join(site, "quartz.config.yaml"), "utf-8"), /my-plugin/)
|
||||
assert.ok(!fs.existsSync(path.join(quartz, "quartz.config.yaml")))
|
||||
// installed into Quartz's .quartz/plugins, where the build loads it
|
||||
assert.ok(fs.existsSync(path.join(quartz, ".quartz", "plugins", "my-plugin")))
|
||||
|
||||
const list = run(quartz, ["plugin", "list", "--config", path.join(site, "quartz.config.yaml")])
|
||||
assert.match(list.stdout, /my-plugin/)
|
||||
|
||||
const missing = run(quartz, ["plugin", "list", "-C", path.join(site, "nope.yaml")])
|
||||
assert.strictEqual(missing.status, 1)
|
||||
assert.match(missing.stderr, /Config file not found/)
|
||||
})
|
||||
})
|
||||
@@ -10,6 +10,7 @@
|
||||
* Overrides are registered under the key the config loader looks them up by: the npm package name
|
||||
* for npm plugins, the directory name for Git/local plugins (#2565).
|
||||
*/
|
||||
import { listPluginDirNames } from "./npm-plugins.js"
|
||||
import fs from "node:fs"
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
@@ -120,20 +121,23 @@ export function collectPluginExports({ pluginsDir, npmPackages = [], verbose = f
|
||||
if (overridable.length > 0 || passthrough.length > 0 || types.length > 0) entries.set(key, info)
|
||||
}
|
||||
|
||||
const dirs = fs.existsSync(pluginsDir)
|
||||
? fs.readdirSync(pluginsDir).filter((n) => fs.statSync(path.join(pluginsDir, n)).isDirectory())
|
||||
: []
|
||||
for (const name of dirs) {
|
||||
const distIndex = path.join(pluginsDir, name, "dist", "index.d.ts")
|
||||
// `name` for Git and local plugins, `@scope/name` for npm plugins pinned in quartz.lock.json
|
||||
const fromDirs = new Set()
|
||||
for (const name of listPluginDirNames(pluginsDir)) {
|
||||
const distIndex = path.join(pluginsDir, ...name.split("/"), "dist", "index.d.ts")
|
||||
if (!fs.existsSync(distIndex)) {
|
||||
if (verbose)
|
||||
console.log(styleText("yellow", `⚠`), `Skipping ${name}: no dist/index.d.ts found`)
|
||||
continue
|
||||
}
|
||||
add(name, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
|
||||
fromDirs.add(name)
|
||||
// a pinned npm plugin keeps its package name as the registry key, as from node_modules
|
||||
const key = name.startsWith("@") ? name.replace(/^@/, "").replace(/\//g, "__") : name
|
||||
add(key, { ...classify(distIndex), importPath: `./${name}`, registryKey: name })
|
||||
}
|
||||
|
||||
for (const pkg of npmPackages) {
|
||||
if (fromDirs.has(pkg)) continue
|
||||
let distIndex
|
||||
try {
|
||||
const pkgJson = fileURLToPath(import.meta.resolve(`${pkg}/package.json`))
|
||||
|
||||
@@ -105,6 +105,24 @@ describe("plugin index", () => {
|
||||
fs.rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("npm plugins pinned in quartz.lock.json are read from .quartz/plugins/@scope/name", () => {
|
||||
const pluginsDir = fs.mkdtempSync(path.join(os.tmpdir(), "quartz-plugin-index-pinned-"))
|
||||
const dist = path.join(pluginsDir, "@me", "widget", "dist")
|
||||
fs.mkdirSync(dist, { recursive: true })
|
||||
fs.writeFileSync(
|
||||
path.join(dist, "index.d.ts"),
|
||||
`import { QuartzComponent } from '@quartz-community/types';\ndeclare const Widget: () => QuartzComponent;\nexport { Widget };\n`,
|
||||
)
|
||||
// also listed by the config as an npm package: read once, from the directory
|
||||
const entries = collectPluginExports({ pluginsDir, npmPackages: ["@me/widget"] })
|
||||
assert.deepStrictEqual([...entries.keys()], ["me__widget"])
|
||||
const entry = entries.get("me__widget")!
|
||||
assert.strictEqual(entry.importPath, "./@me/widget")
|
||||
assert.strictEqual(entry.registryKey, "@me/widget")
|
||||
assert.ok(entry.overridable.includes("Widget"))
|
||||
fs.rmSync(pluginsDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
test("npm plugins register under their package name", () => {
|
||||
const source = renderPluginIndex(
|
||||
new Map([
|
||||
|
||||
@@ -293,6 +293,32 @@ describe("shipped configs", () => {
|
||||
assert.deepStrictEqual([...schemaPositions].sort(), [...LAYOUT_POSITIONS].sort())
|
||||
})
|
||||
|
||||
test("schema has every built-in and font of the configuration", () => {
|
||||
const configuration = schema.properties.configuration.properties
|
||||
for (const key of ["frontmatter", "links", "drafts", "contentIndex", "fonts", "slugs"]) {
|
||||
assert.ok(configuration[key], key)
|
||||
}
|
||||
const typography = configuration.theme.properties.typography.properties
|
||||
assert.deepStrictEqual(Object.keys(typography).sort(), ["body", "code", "header", "title"])
|
||||
assert.strictEqual(typography.header.$ref, "#/$defs/font")
|
||||
const fontObject = schema.$defs.font.oneOf.find((s) => s.type === "object")
|
||||
assert.deepStrictEqual(Object.keys(fontObject.properties).sort(), [
|
||||
"includeItalic",
|
||||
"name",
|
||||
"weights",
|
||||
])
|
||||
})
|
||||
|
||||
test("schema requires a full theme only without extends", () => {
|
||||
// with `extends`, `theme: { colors: { lightMode: { secondary: … } } }` is a whole config
|
||||
const theme = schema.properties.configuration.properties.theme
|
||||
assert.strictEqual(theme.required, undefined)
|
||||
assert.strictEqual(theme.properties.colors.required, undefined)
|
||||
const full = schema.else.properties.configuration.properties.theme
|
||||
assert.deepStrictEqual(full.required, ["fontOrigin", "cdnCaching", "typography", "colors"])
|
||||
assert.deepStrictEqual(full.properties.colors.required, ["lightMode", "darkMode"])
|
||||
})
|
||||
|
||||
for (const file of files) {
|
||||
test(`${path.basename(file)} has no plugin entry problems`, () => {
|
||||
const data = YAML.parse(fs.readFileSync(file, "utf-8"))
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Where a popover goes, and how far its content scrolls to show a heading. Kept out of
|
||||
* popover.inline.ts so tests can import them.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The popover's inline style for a position from floating-ui's `fixed` strategy. The
|
||||
* position is set here, not left to stylesheets: Obsidian's app.css, which quartz-themes-core
|
||||
* bundles for Obsidian themes, makes `.popover` `position: absolute`, and the viewport
|
||||
* coordinates then landed the popover a page's scroll above its link.
|
||||
*/
|
||||
export function popoverPlacement(x: number, y: number) {
|
||||
return {
|
||||
position: "fixed",
|
||||
top: "0",
|
||||
left: "0",
|
||||
transform: `translate(${x.toFixed()}px, ${y.toFixed()}px)`,
|
||||
}
|
||||
}
|
||||
|
||||
interface Box {
|
||||
getBoundingClientRect(): { top: number }
|
||||
}
|
||||
|
||||
/**
|
||||
* The scrollTop that shows `target` `buffer` px below the top of `inner`, measured on screen:
|
||||
* `offsetTop` is relative to the nearest positioned ancestor, which a theme can put inside the
|
||||
* popover (Obsidian themes position `.markdown-preview-view`).
|
||||
*/
|
||||
export function scrollTopFor(inner: Box & { scrollTop: number }, target: Box, buffer = 12) {
|
||||
return (
|
||||
target.getBoundingClientRect().top -
|
||||
inner.getBoundingClientRect().top +
|
||||
inner.scrollTop -
|
||||
buffer
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { computePosition, flip, inline, shift } from "@floating-ui/dom"
|
||||
import { normalizeRelativeURLs } from "../../util/path"
|
||||
import { fetchCanonical } from "./util"
|
||||
import { popoverPlacement, scrollTopFor } from "./popover-layout"
|
||||
|
||||
const p = new DOMParser()
|
||||
let activeAnchor: HTMLAnchorElement | null = null
|
||||
@@ -19,9 +20,7 @@ async function mouseEnterHandler(
|
||||
strategy: "fixed",
|
||||
middleware: [inline({ x: clientX, y: clientY }), shift(), flip()],
|
||||
})
|
||||
Object.assign(popoverElement.style, {
|
||||
transform: `translate(${x.toFixed()}px, ${y.toFixed()}px)`,
|
||||
})
|
||||
Object.assign(popoverElement.style, popoverPlacement(x, y))
|
||||
}
|
||||
|
||||
function showPopover(popoverElement: HTMLElement) {
|
||||
@@ -37,7 +36,7 @@ async function mouseEnterHandler(
|
||||
const heading = inner.querySelector(targetAnchor) as HTMLElement | null
|
||||
if (heading) {
|
||||
// leave ~12px of buffer when scrolling to a heading
|
||||
inner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
|
||||
inner.scroll({ top: scrollTopFor(inner, heading), behavior: "instant" })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { popoverPlacement, scrollTopFor } from "./popover-layout"
|
||||
|
||||
type ScrollArg = { top: number; behavior?: ScrollBehavior }
|
||||
// a heading `offsetTop` px from the top of the popover's content (not scrolled)
|
||||
type FakeHeading = { offsetTop: number }
|
||||
const box = (top: number) => ({ getBoundingClientRect: () => ({ top }) })
|
||||
|
||||
interface FakePopoverInner {
|
||||
scrollTop: number
|
||||
getBoundingClientRect: () => { top: number }
|
||||
scroll: (arg: ScrollArg) => void
|
||||
querySelector: (sel: string) => FakeHeading | null
|
||||
_scrolled: ScrollArg | null
|
||||
@@ -25,6 +30,8 @@ interface FakePopoverElement {
|
||||
|
||||
function makeInner(heading: FakeHeading | null = null): FakePopoverInner {
|
||||
const inner: FakePopoverInner = {
|
||||
scrollTop: 0,
|
||||
getBoundingClientRect: () => ({ top: 0 }),
|
||||
scroll(arg) {
|
||||
this._scrolled = arg
|
||||
},
|
||||
@@ -84,7 +91,7 @@ function fixedShowPopover(
|
||||
const targetAnchor = `#popover-internal-${hash.slice(1)}`
|
||||
const heading = inner.querySelector(targetAnchor)
|
||||
if (heading) {
|
||||
inner.scroll({ top: heading.offsetTop - 12, behavior: "instant" })
|
||||
inner.scroll({ top: scrollTopFor(inner, box(heading.offsetTop)), behavior: "instant" })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,7 +114,7 @@ describe("showPopover on cache-hit with hash", () => {
|
||||
assert.deepStrictEqual(
|
||||
inner._scrolled,
|
||||
{ top: 200 - 12, behavior: "instant" },
|
||||
"scroll must target heading.offsetTop - 12",
|
||||
"scroll must show the heading 12px below the top",
|
||||
)
|
||||
assert.deepStrictEqual(inner._selectorsQueried, ["#popover-internal-plugins"])
|
||||
})
|
||||
@@ -221,3 +228,25 @@ describe("bfcache popover cleanup", () => {
|
||||
assert.strictEqual(queried, false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("popover layout", () => {
|
||||
test("the popover is placed with position: fixed, which its coordinates are for", () => {
|
||||
// Obsidian's app.css (quartz-themes-core) sets .popover { position: absolute }
|
||||
assert.deepStrictEqual(popoverPlacement(764.4, -4.6), {
|
||||
position: "fixed",
|
||||
top: "0",
|
||||
left: "0",
|
||||
transform: "translate(764px, -5px)",
|
||||
})
|
||||
})
|
||||
|
||||
test("scrolls to a heading by its position on screen, not its offsetTop", () => {
|
||||
// the content box starts 100px into the popover (an Obsidian theme positions
|
||||
// .markdown-preview-view, so the heading's offsetTop counts from there)
|
||||
const inner = { scrollTop: 0, ...box(200) }
|
||||
assert.strictEqual(scrollTopFor(inner, box(200 + 100 + 5944)), 100 + 5944 - 12)
|
||||
// already scrolled: the same target
|
||||
const scrolled = { scrollTop: 3000, ...box(200) }
|
||||
assert.strictEqual(scrollTopFor(scrolled, box(200 + 100 + 5944 - 3000)), 100 + 5944 - 12)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import test, { describe } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { i18n, resolveTranslationLocale } from "./index"
|
||||
|
||||
describe("i18n locale fallback", () => {
|
||||
test("a locale with a translation uses it, whatever its case", (t) => {
|
||||
t.mock.method(console, "warn", () => {})
|
||||
assert.strictEqual(resolveTranslationLocale("de-DE"), "de-DE")
|
||||
assert.strictEqual(resolveTranslationLocale("de-de"), "de-DE")
|
||||
assert.strictEqual(resolveTranslationLocale(undefined), "en-US")
|
||||
})
|
||||
|
||||
test("a locale without one uses the same language, else English, and warns once", (t) => {
|
||||
const warn = t.mock.method(console, "warn", () => {})
|
||||
assert.strictEqual(resolveTranslationLocale("es-MX"), "es-ES")
|
||||
assert.strictEqual(resolveTranslationLocale("es-MX"), "es-ES")
|
||||
assert.strictEqual(resolveTranslationLocale("sv-SE"), "en-US")
|
||||
assert.strictEqual(resolveTranslationLocale("nb"), "nb-NO")
|
||||
assert.strictEqual(warn.mock.callCount(), 3)
|
||||
assert.match(String(warn.mock.calls[0]!.arguments[0]), /no translation for locale "es-MX"/)
|
||||
})
|
||||
|
||||
// used to throw: TRANSLATIONS["sv-SE"] was undefined
|
||||
test("i18n() of a locale without a translation returns one", (t) => {
|
||||
t.mock.method(console, "warn", () => {})
|
||||
assert.strictEqual(i18n("da-DK").pages.error.title, i18n("en-US").pages.error.title)
|
||||
})
|
||||
})
|
||||
+28
-1
@@ -85,6 +85,33 @@ export const TRANSLATIONS = {
|
||||
} as const
|
||||
|
||||
export const defaultTranslation = "en-US"
|
||||
export const i18n = (locale: ValidLocale): Translation => TRANSLATIONS[locale ?? defaultTranslation]
|
||||
|
||||
const warnedLocales = new Set<string>()
|
||||
|
||||
/**
|
||||
* The translation to use for `locale`: its own, else one of the same language (`es-MX` uses
|
||||
* `es-ES`), else English. A locale without a translation used to crash the build
|
||||
* (`TRANSLATIONS[locale]` is undefined); dates and numbers still use the configured locale.
|
||||
*/
|
||||
export function resolveTranslationLocale(locale: string | undefined): ValidLocale {
|
||||
if (!locale) return defaultTranslation
|
||||
const keys = Object.keys(TRANSLATIONS) as ValidLocale[]
|
||||
const exact = keys.find((key) => key.toLowerCase() === locale.toLowerCase())
|
||||
if (exact) return exact
|
||||
const language = locale.split("-")[0]!.toLowerCase()
|
||||
const chosen =
|
||||
keys.find((key) => key.split("-")[0]!.toLowerCase() === language) ?? defaultTranslation
|
||||
if (!warnedLocales.has(locale)) {
|
||||
warnedLocales.add(locale)
|
||||
console.warn(
|
||||
`Quartz has no translation for locale "${locale}"; its text uses ${chosen}. ` +
|
||||
`Dates still use ${locale}. Translations: https://quartz.jzhao.xyz/features/i18n`,
|
||||
)
|
||||
}
|
||||
return chosen
|
||||
}
|
||||
|
||||
export const i18n = (locale: ValidLocale | string | undefined): Translation =>
|
||||
TRANSLATIONS[resolveTranslationLocale(locale)]
|
||||
export type ValidLocale = keyof typeof TRANSLATIONS
|
||||
export type ValidCallout = keyof CalloutTranslation
|
||||
@@ -435,6 +435,107 @@ describe("links built-in", () => {
|
||||
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
|
||||
})
|
||||
|
||||
// #2725: resolved as Obsidian does (utils 1.3.5)
|
||||
test("a ./ link is in the page's folder, under every strategy", () => {
|
||||
for (const markdownLinkResolution of ["shortest", "absolute", "relative"]) {
|
||||
const { els, file } = run(
|
||||
[a("./index", "index"), a("./sibling")],
|
||||
"folder/special",
|
||||
{ markdownLinkResolution },
|
||||
["index", "folder/index", "folder/special", "folder/sibling", "sibling"],
|
||||
)
|
||||
const [index, sibling] = els.filter((e) => e.tagName === "a")
|
||||
assert.strictEqual(index.properties.href, "./", markdownLinkResolution)
|
||||
assert.strictEqual(index.properties["data-slug"], "folder/index", markdownLinkResolution)
|
||||
assert.strictEqual(sibling.properties["data-slug"], "folder/sibling", markdownLinkResolution)
|
||||
// the folder page, not the home page
|
||||
assert.ok(file.data.links?.includes("folder/" as SimpleSlug), markdownLinkResolution)
|
||||
}
|
||||
})
|
||||
|
||||
test("of several pages with a name, the one under the page's folder, else the shortest path", () => {
|
||||
const allSlugs = [
|
||||
"index",
|
||||
"projects/alpha/index",
|
||||
"projects/alpha/current",
|
||||
"projects/beta/index",
|
||||
"projects/beta/current",
|
||||
]
|
||||
const opts = { markdownLinkResolution: "shortest" }
|
||||
const slugOf = (src: string, target: string) =>
|
||||
run([a(target)], src, opts, allSlugs).els[0]!.properties["data-slug"]
|
||||
// relative-mode vaults write a note in the same folder as a bare name
|
||||
assert.strictEqual(slugOf("projects/alpha/index", "current.md"), "projects/alpha/current")
|
||||
assert.strictEqual(slugOf("projects/beta/index", "current"), "projects/beta/current")
|
||||
// from elsewhere, the shortest path (Obsidian sorts by path length)
|
||||
assert.strictEqual(slugOf("index", "current"), "projects/beta/current")
|
||||
})
|
||||
|
||||
describe("aliases", () => {
|
||||
// getting-started/upgrading.md has `aliases: [upgrading]`; guide.md has `aliases: [How To]`
|
||||
const aliasCtx = (extra: Record<string, unknown> = {}) =>
|
||||
({
|
||||
allSlugs: [
|
||||
"index",
|
||||
"getting-started/upgrading",
|
||||
"guide",
|
||||
"notes/how-to",
|
||||
"upgrading",
|
||||
"how-to",
|
||||
],
|
||||
aliases: { upgrading: "getting-started/upgrading", "how-to": "guide" },
|
||||
...extra,
|
||||
}) as unknown as BuildCtx
|
||||
const resolve = (links: Element[], slug = "getting-started/whats-new", ctx = aliasCtx()) => {
|
||||
const tree: Root = { type: "root", children: links }
|
||||
const file = new VFile("")
|
||||
file.data = { slug: slug as FullSlug }
|
||||
const [factory] = Links({ markdownLinkResolution: "shortest" }).htmlPlugins!(ctx) as [
|
||||
() => (t: Root, f: VFile) => void,
|
||||
]
|
||||
factory()(tree, file)
|
||||
return { links: tree.children as Element[], file }
|
||||
}
|
||||
|
||||
test("a link with an alias's name goes to the page, keeping its anchor", () => {
|
||||
const { links, file } = resolve(
|
||||
[a("upgrading#upgrading-from-52-to-53", "Upgrading")],
|
||||
"index",
|
||||
)
|
||||
// not ./upgrading#…: the alias's redirect page would drop the anchor
|
||||
assert.strictEqual(
|
||||
links[0]!.properties.href,
|
||||
"./getting-started/upgrading#upgrading-from-52-to-53",
|
||||
)
|
||||
assert.strictEqual(links[0]!.properties["data-slug"], "getting-started/upgrading")
|
||||
// backlinks and the graph see a link to the page
|
||||
assert.deepStrictEqual(file.data.links, ["getting-started/upgrading"])
|
||||
})
|
||||
|
||||
test("a page beats an alias with its name, as in Obsidian", () => {
|
||||
// `How To` is an alias of guide.md, but notes/how-to.md is a note with that name
|
||||
const { links } = resolve([a("how-to")], "index")
|
||||
assert.strictEqual(links[0]!.properties["data-slug"], "notes/how-to")
|
||||
})
|
||||
|
||||
test("a name only an alias has goes to its page", () => {
|
||||
const ctx = aliasCtx({
|
||||
allSlugs: ["index", "guide", "how-to"],
|
||||
aliases: { "how-to": "guide" },
|
||||
})
|
||||
const { links } = resolve([a("how-to#step-2", "How To")], "notes/page", ctx)
|
||||
assert.strictEqual(links[0]!.properties.href, "../guide#step-2")
|
||||
assert.ok(!(links[0]!.properties.className as string[]).includes("broken"))
|
||||
})
|
||||
|
||||
test("an alias named like an Object property is still an alias", () => {
|
||||
const ctx = aliasCtx({ allSlugs: ["index", "guide"], aliases: {} })
|
||||
const { links } = resolve([a("constructor")], "index", ctx)
|
||||
assert.strictEqual(links[0]!.properties["data-slug"], "constructor")
|
||||
assert.ok((links[0]!.properties.className as string[]).includes("broken"))
|
||||
})
|
||||
})
|
||||
|
||||
test("slugs.stripDiacritics: link targets are stripped like the slugs they point at (#2410)", () => {
|
||||
setSlugOptions({ stripDiacritics: true })
|
||||
try {
|
||||
@@ -451,7 +552,8 @@ describe("links built-in", () => {
|
||||
["ceske/page", "ceske/cestina", "jine/prilis", "ceske/obrazek.png"],
|
||||
)
|
||||
const [cestina, prilis] = els.filter((e) => e.tagName === "a")
|
||||
assert.strictEqual(cestina.properties.href, "../ceske/cestina#český-nadpis")
|
||||
// ./ is relative to ceske/page (utils 1.3.5): the same page as ../ceske/cestina
|
||||
assert.strictEqual(cestina.properties.href, "./cestina#český-nadpis")
|
||||
assert.ok(!(cestina.properties.className as string[]).includes("broken"))
|
||||
assert.strictEqual(prilis.properties.href, "../jine/prilis")
|
||||
assert.strictEqual(
|
||||
|
||||
@@ -58,6 +58,12 @@ function getAliasSlugs(aliases: string[]): FullSlug[] {
|
||||
})
|
||||
}
|
||||
|
||||
/** Slugs of the `aliases` (or `alias`) in raw frontmatter, as {@link normalizeFrontmatter} reads them. */
|
||||
export function aliasSlugsOf(data: Record<string, unknown>): FullSlug[] {
|
||||
const aliases = coerceToArray(coalesceAliases(data, ["aliases", "alias"]))
|
||||
return aliases ? getAliasSlugs(aliases) : []
|
||||
}
|
||||
|
||||
/** `[[Some Note#Heading]]` target → `some-note#heading` (same slugging as wikilinks). */
|
||||
export function slugifyWikilinkTarget(target: string): string {
|
||||
const [rawPath, anchor] = splitAnchor(target)
|
||||
|
||||
@@ -112,6 +112,29 @@ export function linkTargetMissing(allSlugs: readonly string[], full: string): bo
|
||||
return VAULT_FILE_TYPES.has(ext)
|
||||
}
|
||||
|
||||
/**
|
||||
* `allSlugs` without alias addresses (see util/aliases.ts), for resolving links against pages.
|
||||
* Cached: `allSlugs` only grows while files are parsed, and `aliases` is replaced on a rebuild.
|
||||
*/
|
||||
let pageSlugsCache: {
|
||||
from: readonly string[]
|
||||
length: number
|
||||
aliases: object
|
||||
slugs: FullSlug[]
|
||||
} = { from: [], length: -1, aliases: {}, slugs: [] }
|
||||
/** The page an alias slug belongs to (own keys only: `constructor` is a fine slug). */
|
||||
const aliasTarget = (aliases: Record<string, FullSlug>, slug: string): FullSlug | undefined =>
|
||||
Object.hasOwn(aliases, slug) ? aliases[slug] : undefined
|
||||
|
||||
export function pageSlugs(allSlugs: FullSlug[], aliases: Record<string, FullSlug>): FullSlug[] {
|
||||
if (Object.keys(aliases).length === 0) return allSlugs
|
||||
const c = pageSlugsCache
|
||||
if (c.from === allSlugs && c.length === allSlugs.length && c.aliases === aliases) return c.slugs
|
||||
const slugs = allSlugs.filter((slug) => !Object.hasOwn(aliases, slug))
|
||||
pageSlugsCache = { from: allSlugs, length: allSlugs.length, aliases, slugs }
|
||||
return slugs
|
||||
}
|
||||
|
||||
/** The `broken` mark added after filtering, so a later rebuild can take it off again. */
|
||||
const FILTERED_ATTR = "data-filtered"
|
||||
/** The `broken` mark for links to folder and tag pages that no page type generated. */
|
||||
@@ -258,13 +281,29 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
|
||||
? slugifyFilePath(file.data.relativePath)
|
||||
: fileSlug
|
||||
const rebase = targets.size > 0 || pathSlug !== fileSlug
|
||||
// Aliases: links resolve against the site's pages first (in Obsidian aliases aren't
|
||||
// link targets, so `[[upgrading]]` is the note `getting-started/upgrading`, not the
|
||||
// alias `upgrading` of some note). A link only an alias matches goes straight to the
|
||||
// page with the alias, keeping its anchor, which the alias's redirect page drops.
|
||||
const aliases = ctx.aliases ?? {}
|
||||
const pageOptions: TransformOptions = {
|
||||
...transformOptions,
|
||||
allSlugs: pageSlugs(ctx.allSlugs, aliases),
|
||||
}
|
||||
const resolveLink = (raw: string): RelativeURL => {
|
||||
const rel = transformLink(pathSlug, raw, transformOptions)
|
||||
if (!rebase) return rel
|
||||
let rel = transformLink(pathSlug, raw, pageOptions)
|
||||
let target = canonicalSlug(rel, simplifySlug(pathSlug))
|
||||
let page = aliasTarget(aliases, target)
|
||||
if (page === undefined && linkTargetMissing(pageOptions.allSlugs, target)) {
|
||||
// a name only an alias has, resolved like a page's (e.g. a path alias `a/b`)
|
||||
rel = transformLink(pathSlug, raw, transformOptions)
|
||||
target = canonicalSlug(rel, simplifySlug(pathSlug))
|
||||
page = aliasTarget(aliases, target)
|
||||
}
|
||||
if (page === undefined && !rebase) return rel
|
||||
const hash = rel.indexOf("#")
|
||||
const anchor = hash === -1 ? "" : rel.slice(hash)
|
||||
const target = canonicalSlug(rel, simplifySlug(pathSlug))
|
||||
return (resolveRelative(fileSlug, targets.get(target) ?? target) +
|
||||
return (resolveRelative(fileSlug, page ?? targets.get(target) ?? target) +
|
||||
anchor) as RelativeURL
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ describe("SlugRedirects emitter", () => {
|
||||
<link rel="canonical" href="${url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<script>location.replace(${JSON.stringify(url)} + location.hash)</script>
|
||||
<meta http-equiv="refresh" content="0; url=${url}">
|
||||
</head>
|
||||
</html>
|
||||
|
||||
@@ -73,6 +73,7 @@ function redirectHtml(to: string, url: string): string {
|
||||
<link rel="canonical" href="${url}">
|
||||
<meta name="robots" content="noindex">
|
||||
<meta charset="utf-8">
|
||||
<script>location.replace(${JSON.stringify(url).replace(/</g, "\\u003c")} + location.hash)</script>
|
||||
<meta http-equiv="refresh" content="0; url=${url}">
|
||||
</head>
|
||||
</html>
|
||||
|
||||
@@ -379,6 +379,70 @@ describe("resolveExtends", () => {
|
||||
)
|
||||
})
|
||||
|
||||
describe("keys starting with $ are reserved", () => {
|
||||
const own = path.join(root, "quartz.config.yaml")
|
||||
const opts = { quartzRoot: root, readFile }
|
||||
|
||||
test("in the extending file, at any depth", async () => {
|
||||
for (const [data, where] of [
|
||||
[
|
||||
{ configuration: { ignorePatterns: { $append: ["drafts"] } } },
|
||||
"configuration.ignorePatterns.$append",
|
||||
],
|
||||
[{ configuration: { $pageTitle: "x" } }, "configuration.$pageTitle"],
|
||||
[
|
||||
{ layout: { byPageType: { folder: { $exclude: [] } } } },
|
||||
"layout.byPageType.folder.$exclude",
|
||||
],
|
||||
[
|
||||
{ plugins: [{ source: "@quartz-community/explorer", options: { $merge: {} } }] },
|
||||
"plugins.0.options.$merge",
|
||||
],
|
||||
[
|
||||
{ plugins: [{ source: "@quartz-community/explorer", $remove: true }] },
|
||||
"plugins.0.$remove",
|
||||
],
|
||||
[{ $plugins: [] }, "$plugins"],
|
||||
] as const) {
|
||||
await assert.rejects(
|
||||
() => resolveExtends({ extends: "default", ...data }, own, opts),
|
||||
{
|
||||
name: "ConfigExtendsError",
|
||||
message: `${own}: "${where}" — keys starting with "$" are reserved in configs that use "extends"`,
|
||||
},
|
||||
where,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test("in a base the config extends", async () => {
|
||||
put("preset.yaml", { extends: "default", configuration: { $x: 1 } })
|
||||
await assert.rejects(
|
||||
() => resolveExtends({ extends: "./preset.yaml" }, own, opts),
|
||||
/preset\.yaml: "configuration\.\$x" — keys starting with "\$" are reserved/,
|
||||
)
|
||||
})
|
||||
|
||||
test("the top-level $schema is allowed, and $ inside values is fine", async () => {
|
||||
const merged = await resolveExtends(
|
||||
{
|
||||
$schema: "./quartz/plugins/quartz-plugins.schema.json",
|
||||
extends: "default",
|
||||
configuration: { pageTitle: "$5 tips", ignorePatterns: ["$tmp"] },
|
||||
},
|
||||
own,
|
||||
opts,
|
||||
)
|
||||
assert.strictEqual(merged.configuration.pageTitle, "$5 tips")
|
||||
assert.deepStrictEqual(merged.configuration.ignorePatterns, ["$tmp"])
|
||||
})
|
||||
|
||||
test("a config without extends is not checked", async () => {
|
||||
const data = { configuration: { pageTitle: "x", $custom: 1 }, plugins: [] }
|
||||
assert.strictEqual(await resolveExtends(data, own, opts), data as never)
|
||||
})
|
||||
})
|
||||
|
||||
test("a base that is not a configuration object is an error", async () => {
|
||||
files[path.join(root, "list.yaml")] = "- source: explorer\n- source: graph\n"
|
||||
const file = path.join(root, "list.yaml")
|
||||
|
||||
@@ -342,6 +342,32 @@ export function resolveTarget(target: string, from: string, quartzRoot: string):
|
||||
return resolved
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys starting with `$` are reserved in every file of an `extends` chain (the top-level
|
||||
* `$schema` aside), at any depth: they are kept free for merge operators, such as appending
|
||||
* to a list instead of replacing it, so adding those later changes no existing config.
|
||||
*/
|
||||
export const RESERVED_KEY_PREFIX = "$"
|
||||
|
||||
function assertNoReservedKeys(data: PlainObject, file: string) {
|
||||
const visit = (value: unknown, at: string[]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item, i) => visit(item, [...at, String(i)]))
|
||||
return
|
||||
}
|
||||
if (!isPlainObject(value)) return
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (key.startsWith(RESERVED_KEY_PREFIX) && !(at.length === 0 && key === "$schema")) {
|
||||
throw new ConfigExtendsError(
|
||||
`${file}: "${[...at, key].join(".")}" — keys starting with "${RESERVED_KEY_PREFIX}" are reserved in configs that use "extends"`,
|
||||
)
|
||||
}
|
||||
visit(child, [...at, key])
|
||||
}
|
||||
}
|
||||
visit(data, [])
|
||||
}
|
||||
|
||||
interface ConfigLayer {
|
||||
/** Resolved path or URL ("" for the config being resolved). */
|
||||
file: string
|
||||
@@ -443,6 +469,7 @@ async function extendsLayers(
|
||||
await visit(parsed, targetFile, here)
|
||||
}
|
||||
const { extends: _drop, ...own } = node
|
||||
assertNoReservedKeys(own, nodeFile)
|
||||
layers.push({ file: chain.length === 0 ? "" : self, data: own })
|
||||
applied.add(self)
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
getPluginEntryPoint,
|
||||
toFileUrl,
|
||||
isLocalSource,
|
||||
linkPeerDependencies,
|
||||
} from "./gitLoader"
|
||||
import { loadComponentsFromPackage } from "./componentLoader"
|
||||
import { attributeComponentExport, shortPluginName } from "../../components/attribution"
|
||||
@@ -50,6 +51,16 @@ import {
|
||||
} from "../builtins"
|
||||
import { registerPluginOrigin, reportError, warn } from "../../util/diagnostics"
|
||||
import { firstPluginFrame } from "../../util/trace"
|
||||
import { currentLockfilePath } from "../../cli/lockfile-path.js"
|
||||
import {
|
||||
ensureNpmPlugin,
|
||||
isHostDependency,
|
||||
isPinnedNpmPluginInstalled,
|
||||
npmPackageName,
|
||||
npmPluginDir,
|
||||
readNpmLockEntry,
|
||||
removeNpmPlugin,
|
||||
} from "../../cli/npm-plugins.js"
|
||||
import {
|
||||
checkQuartzRequirement,
|
||||
describeDeprecation,
|
||||
@@ -303,11 +314,22 @@ export function validateDependencies(
|
||||
* so their init(options) and entry-module side effects never ran.)
|
||||
*/
|
||||
async function importPluginModule(spec: ReturnType<typeof parsePluginSource>) {
|
||||
return spec.npmPackage
|
||||
return spec.npmPackage && !isPinnedNpm(spec)
|
||||
? await import(spec.name)
|
||||
: await import(toFileUrl(getPluginEntryPoint(spec.name)))
|
||||
}
|
||||
|
||||
const PLUGINS_DIR = path.join(process.cwd(), ".quartz", "plugins")
|
||||
|
||||
/**
|
||||
* An npm plugin pinned in quartz.lock.json and installed in .quartz/plugins/@scope/name, because
|
||||
* package.json doesn't list it (see cli/npm-plugins.js). One that package.json lists loads from
|
||||
* node_modules.
|
||||
*/
|
||||
function isPinnedNpm(spec: ReturnType<typeof parsePluginSource>): boolean {
|
||||
return !!spec.npmPackage && isPinnedNpmPluginInstalled(npmPackageName(spec.name), PLUGINS_DIR)
|
||||
}
|
||||
|
||||
async function resolvePluginManifest(source: PluginSource): Promise<PluginManifest | null> {
|
||||
try {
|
||||
const module = await importPluginModule(parsePluginSource(source))
|
||||
@@ -321,7 +343,7 @@ async function readManifestFromPackageJson(source: PluginSource): Promise<Plugin
|
||||
try {
|
||||
const gitSpec = parsePluginSource(source)
|
||||
let pkgPath: string
|
||||
if (gitSpec.npmPackage) {
|
||||
if (gitSpec.npmPackage && !isPinnedNpm(gitSpec)) {
|
||||
pkgPath = fileURLToPath(import.meta.resolve(`${gitSpec.name}/package.json`))
|
||||
} else {
|
||||
const pluginDir = path.join(process.cwd(), ".quartz", "plugins", gitSpec.name)
|
||||
@@ -438,6 +460,19 @@ export async function loadQuartzConfig(
|
||||
try {
|
||||
const gitSpec = parsePluginSource(entry.source)
|
||||
if (gitSpec.npmPackage) {
|
||||
// npm plugins package.json doesn't list: installed at the version quartz.lock.json pins
|
||||
// (the latest when it pins none), as a missing Git plugin is cloned below
|
||||
const name = npmPackageName(gitSpec.name)
|
||||
if (isHostDependency(name)) {
|
||||
// package.json wins: a copy left from when it was pinned would shadow its components
|
||||
removeNpmPlugin(name, PLUGINS_DIR)
|
||||
continue
|
||||
}
|
||||
const installed = ensureNpmPlugin(name, {
|
||||
lockEntry: readNpmLockEntry(name, currentLockfilePath()),
|
||||
pluginsDir: PLUGINS_DIR,
|
||||
})
|
||||
if (installed) linkPeerDependencies(npmPluginDir(name, PLUGINS_DIR))
|
||||
continue
|
||||
}
|
||||
const result = await installPlugin(gitSpec, { verbose: false })
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
npm,
|
||||
} from "../../cli/subprocess.js"
|
||||
import { writePluginIndex } from "../../cli/plugin-index.js"
|
||||
import { listPluginDirNames } from "../../cli/npm-plugins.js"
|
||||
import { currentLockfilePath } from "../../cli/lockfile-path.js"
|
||||
import git from "isomorphic-git"
|
||||
import http from "isomorphic-git/http/node"
|
||||
import { styleText } from "util"
|
||||
@@ -46,7 +48,6 @@ export interface GitPluginSpec {
|
||||
export type PluginInstallSource = string | GitPluginSpec
|
||||
|
||||
const PLUGINS_CACHE_DIR = path.join(process.cwd(), ".quartz", "plugins")
|
||||
const LOCKFILE_PATH = path.join(process.cwd(), "quartz.lock.json")
|
||||
const GIT_TIMEOUT_MS = 300_000
|
||||
|
||||
/**
|
||||
@@ -55,7 +56,7 @@ const GIT_TIMEOUT_MS = 300_000
|
||||
*/
|
||||
export function readLockedCommit(
|
||||
spec: Pick<GitPluginSpec, "name" | "repo" | "subdir">,
|
||||
lockfilePath: string = LOCKFILE_PATH,
|
||||
lockfilePath: string = currentLockfilePath(),
|
||||
): string | undefined {
|
||||
try {
|
||||
const lock = JSON.parse(fs.readFileSync(lockfilePath, "utf-8"))
|
||||
@@ -366,12 +367,8 @@ function needsBuild(pluginDir: string): boolean {
|
||||
function findPluginByPackageName(packageName: string): string | null {
|
||||
if (!fs.existsSync(PLUGINS_CACHE_DIR)) return null
|
||||
|
||||
const plugins = fs.readdirSync(PLUGINS_CACHE_DIR).filter((entry) => {
|
||||
const entryPath = path.join(PLUGINS_CACHE_DIR, entry)
|
||||
return fs.statSync(entryPath).isDirectory()
|
||||
})
|
||||
|
||||
for (const pluginDirName of plugins) {
|
||||
// `name` for Git and local plugins, `@scope/name` for pinned npm plugins
|
||||
for (const pluginDirName of listPluginDirNames(PLUGINS_CACHE_DIR)) {
|
||||
const pkgPath = path.join(PLUGINS_CACHE_DIR, pluginDirName, "package.json")
|
||||
if (!fs.existsSync(pkgPath)) continue
|
||||
try {
|
||||
@@ -406,7 +403,12 @@ export function linkPeerDependencies(pluginDir: string): void {
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"))
|
||||
const peers: Record<string, string> = pkg.peerDependencies ?? {}
|
||||
|
||||
const quartzRoot = path.resolve(pluginDir, "..", "..", "..")
|
||||
// .quartz/plugins/<name>, or .quartz/plugins/@scope/<name> for a pinned npm plugin
|
||||
const scoped = path.basename(path.dirname(pluginDir)).startsWith("@")
|
||||
const quartzRoot = path.resolve(
|
||||
pluginDir,
|
||||
...(scoped ? ["..", "..", "..", ".."] : ["..", "..", ".."]),
|
||||
)
|
||||
const hostNodeModules = path.join(quartzRoot, "node_modules")
|
||||
// a local plugin is a symlink; relative links made through it would dangle
|
||||
const realDir = fs.realpathSync(pluginDir)
|
||||
|
||||
@@ -2,7 +2,21 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import YAML from "yaml"
|
||||
import { installPlugins, parsePluginSource, regeneratePluginIndex } from "./gitLoader.js"
|
||||
import {
|
||||
installPlugins,
|
||||
linkPeerDependencies,
|
||||
parsePluginSource,
|
||||
regeneratePluginIndex,
|
||||
} from "./gitLoader.js"
|
||||
import {
|
||||
ensureNpmPlugin,
|
||||
isHostDependency,
|
||||
npmPackageName,
|
||||
npmPluginDir,
|
||||
readNpmLockEntry,
|
||||
removeNpmPlugin,
|
||||
} from "../../cli/npm-plugins.js"
|
||||
import { currentLockfilePath } from "../../cli/lockfile-path.js"
|
||||
import type { PluginSource, QuartzPluginsJson } from "./types.js"
|
||||
import { absorbingBuiltin } from "../builtins/index.js"
|
||||
import { resolveExtends } from "./config-extends.js"
|
||||
@@ -89,8 +103,27 @@ async function main() {
|
||||
}
|
||||
|
||||
if (npmSpecs.length > 0) {
|
||||
// npm plugins package.json doesn't list are pinned in quartz.lock.json and installed into
|
||||
// .quartz/plugins/@scope/name (see cli/npm-plugins.js); the others come from node_modules
|
||||
const pluginsDir = path.join(process.cwd(), ".quartz", "plugins")
|
||||
const lockfile = currentLockfilePath()
|
||||
const hostPackages: string[] = []
|
||||
for (const spec of npmSpecs) {
|
||||
const name = npmPackageName(spec.name)
|
||||
if (isHostDependency(name)) {
|
||||
removeNpmPlugin(name, pluginsDir)
|
||||
hostPackages.push(spec.name)
|
||||
continue
|
||||
}
|
||||
const lockEntry = readNpmLockEntry(name, lockfile)
|
||||
const installed = ensureNpmPlugin(name, { lockEntry, pluginsDir, verbose: true })
|
||||
if (installed) {
|
||||
linkPeerDependencies(npmPluginDir(name, pluginsDir))
|
||||
console.log(`✓ Installed ${name}@${installed.version} from npm`)
|
||||
}
|
||||
}
|
||||
console.log(`Found ${npmSpecs.length} npm plugin(s), regenerating plugin index...`)
|
||||
await regeneratePluginIndex({ verbose: true, npmPackages: npmSpecs.map((s) => s.name) })
|
||||
await regeneratePluginIndex({ verbose: true, npmPackages: hostPackages })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,17 @@
|
||||
"required": ["configuration", "plugins"],
|
||||
"properties": {
|
||||
"configuration": {
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"]
|
||||
"required": ["pageTitle", "enableSPA", "locale", "theme"],
|
||||
"properties": {
|
||||
"theme": {
|
||||
"required": ["fontOrigin", "cdnCaching", "typography", "colors"],
|
||||
"properties": {
|
||||
"colors": {
|
||||
"required": ["lightMode", "darkMode"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"items": {
|
||||
@@ -35,7 +45,7 @@
|
||||
"description": "JSON Schema reference"
|
||||
},
|
||||
"extends": {
|
||||
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml) or a path relative to this file, or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Without extends, this file is the whole configuration.",
|
||||
"description": "Start from another config and apply this file on top: \"default\" (quartz.config.default.yaml), a path relative to this file, an https:// URL (experimental), or a list of them (later ones win). Objects merge key by key, other values replace, null removes a key; plugin entries match the base entry of the same plugin by name. Keys starting with $ are reserved (except $schema). Without extends, this file is the whole configuration.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
@@ -85,7 +95,6 @@
|
||||
},
|
||||
"theme": {
|
||||
"type": "object",
|
||||
"required": ["fontOrigin", "cdnCaching", "typography", "colors"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"fontOrigin": {
|
||||
@@ -101,23 +110,26 @@
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"title": {
|
||||
"description": "Font for the site title (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"header": {
|
||||
"type": "string",
|
||||
"description": "Font family for headers"
|
||||
"description": "Font for headers",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"body": {
|
||||
"type": "string",
|
||||
"description": "Font family for body text"
|
||||
"description": "Font for body text",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"code": {
|
||||
"type": "string",
|
||||
"description": "Font family for code"
|
||||
"description": "Font for code",
|
||||
"$ref": "#/$defs/font"
|
||||
}
|
||||
}
|
||||
},
|
||||
"colors": {
|
||||
"type": "object",
|
||||
"required": ["lightMode", "darkMode"],
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"lightMode": {
|
||||
@@ -404,6 +416,80 @@
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"fonts": {
|
||||
"description": "Built-in font loading (formerly the quartz-fonts plugin): Google Fonts, self-hosted or local, and per-heading fonts.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "boolean"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean",
|
||||
"description": "Set to false to turn this built-in off (e.g. to replace it with a plugin)."
|
||||
},
|
||||
"order": {
|
||||
"type": "number",
|
||||
"description": "Position among plugins of the same category (same scale as plugin `order`)."
|
||||
},
|
||||
"fontOrigin": {
|
||||
"enum": ["googleFonts", "selfHosted", "local"],
|
||||
"description": "Where fonts load from: Google Fonts (default), downloaded at build time and served from the site (selfHosted), or not loaded at all (local)."
|
||||
},
|
||||
"title": {
|
||||
"description": "Overrides theme.typography.title",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"header": {
|
||||
"description": "Overrides theme.typography.header",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"body": {
|
||||
"description": "Overrides theme.typography.body",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"code": {
|
||||
"description": "Overrides theme.typography.code",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"interface": {
|
||||
"description": "Font for interface elements (Obsidian's --font-interface)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"h1": {
|
||||
"description": "Font for h1 headings (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"h2": {
|
||||
"description": "Font for h2 headings (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"h3": {
|
||||
"description": "Font for h3 headings (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"h4": {
|
||||
"description": "Font for h4 headings (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"h5": {
|
||||
"description": "Font for h5 headings (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"h6": {
|
||||
"description": "Font for h6 headings (default: the header font)",
|
||||
"$ref": "#/$defs/font"
|
||||
},
|
||||
"useThemeFonts": {
|
||||
"type": "boolean",
|
||||
"description": "Use the fonts of a theme plugin such as @quartz-themes/core. Default true."
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -674,5 +760,37 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"font": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["name"],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Font family (any Google Font)"
|
||||
},
|
||||
"weights": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "number"
|
||||
},
|
||||
"description": "Font weights to load"
|
||||
},
|
||||
"includeItalic": {
|
||||
"type": "boolean",
|
||||
"description": "Also load the italic styles"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"description": "A font name (any Google Font), or { name, weights, includeItalic }"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, test } from "node:test"
|
||||
import assert from "node:assert"
|
||||
import { collectAliases } from "./aliases"
|
||||
import { FullSlug } from "./path"
|
||||
|
||||
describe("collectAliases", () => {
|
||||
const files = [
|
||||
"index.md",
|
||||
"getting-started/upgrading.md",
|
||||
"guide.md",
|
||||
"notes/how-to.md",
|
||||
"moved.md",
|
||||
"img/how-to.png",
|
||||
]
|
||||
const frontmatter: Record<string, string[]> = {
|
||||
"getting-started/upgrading.md": ["upgrading", "getting-started/upgrading"],
|
||||
"guide.md": ["how-to", "guide-old", "notes/how-to", "img/how-to.png"],
|
||||
"moved.md": ["guide-old", "previous"],
|
||||
}
|
||||
const aliases = collectAliases({
|
||||
files,
|
||||
aliasesOf: (file) => (frontmatter[file] ?? []) as FullSlug[],
|
||||
permalinks: { "moved.md": "elsewhere/moved" as FullSlug },
|
||||
})
|
||||
|
||||
test("maps each alias to the page that has it, at its published address", () => {
|
||||
assert.deepStrictEqual(aliases, {
|
||||
upgrading: "getting-started/upgrading",
|
||||
"how-to": "guide",
|
||||
"guide-old": "guide",
|
||||
previous: "elsewhere/moved",
|
||||
})
|
||||
})
|
||||
|
||||
test("a page's address is never an alias: its own path, another page's or a file's", () => {
|
||||
for (const slug of ["getting-started/upgrading", "notes/how-to", "img/how-to.png"]) {
|
||||
assert.ok(!Object.hasOwn(aliases, slug), slug)
|
||||
}
|
||||
})
|
||||
|
||||
test("of two notes with an alias, the first keeps it", () => {
|
||||
assert.strictEqual(aliases["guide-old"], "guide")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import { FilePath, FullSlug, slugifyFilePath } from "./path"
|
||||
import { Permalinks, slugForFile } from "./permalinks"
|
||||
|
||||
/**
|
||||
* Frontmatter `aliases`: alias slug → the slug of the page that has the alias.
|
||||
*
|
||||
* An alias is an extra address of a note: the alias-redirects plugin writes a redirect page
|
||||
* there. Links resolve against real pages first (as in Obsidian, where aliases are not link
|
||||
* targets), and a link that only an alias matches goes straight to the page, so an `#anchor`
|
||||
* survives (a redirect page drops it). Like permalinks, aliases are collected up front, so every
|
||||
* worker thread knows all of them, not only those of the files it parsed.
|
||||
*/
|
||||
export type Aliases = Record<string, FullSlug>
|
||||
|
||||
export interface CollectAliasesOptions {
|
||||
/** All content files, relative to the content directory. */
|
||||
files: string[]
|
||||
/** Alias slugs of a Markdown file (from its frontmatter); empty when it has none. */
|
||||
aliasesOf: (file: string) => readonly FullSlug[]
|
||||
permalinks?: Permalinks
|
||||
}
|
||||
|
||||
/**
|
||||
* Aliases of `files`. An alias that is a page's address (a file path or a permalink) is left
|
||||
* out: the page wins, as the redirect pages never replace a page either. Of two notes with the
|
||||
* same alias, the first keeps it.
|
||||
*/
|
||||
export function collectAliases({ files, aliasesOf, permalinks }: CollectAliasesOptions): Aliases {
|
||||
const pages = new Set<string>(files.map((f) => slugifyFilePath(f as FilePath)))
|
||||
for (const slug of Object.values(permalinks ?? {})) pages.add(slug)
|
||||
const aliases: Aliases = {}
|
||||
for (const file of files) {
|
||||
if (!file.endsWith(".md")) continue
|
||||
const page = slugForFile(file, permalinks)
|
||||
for (const alias of aliasesOf(file)) {
|
||||
if (alias === page || pages.has(alias) || Object.hasOwn(aliases, alias)) continue
|
||||
aliases[alias] = page
|
||||
}
|
||||
}
|
||||
return aliases
|
||||
}
|
||||
@@ -11,6 +11,7 @@ describe("workerCtx", () => {
|
||||
allSlugs: ["index", "elsewhere/moved"] as FullSlug[],
|
||||
allFiles: ["index.md", "Moved.md"] as FilePath[],
|
||||
permalinks: { "Moved.md": "elsewhere/moved" as FullSlug },
|
||||
aliases: { "old-name": "index" as FullSlug },
|
||||
incremental: false,
|
||||
virtualPages: [],
|
||||
trie: {},
|
||||
@@ -20,6 +21,10 @@ describe("workerCtx", () => {
|
||||
assert.deepStrictEqual(workerCtx(ctx).permalinks, { "Moved.md": "elsewhere/moved" })
|
||||
})
|
||||
|
||||
test("carries aliases to worker threads", () => {
|
||||
assert.deepStrictEqual(workerCtx(ctx).aliases, { "old-name": "index" })
|
||||
})
|
||||
|
||||
test("holds plain data only, and survives structured cloning", () => {
|
||||
const worker = workerCtx(ctx)
|
||||
assert.ok(!("cfg" in worker) && !("trie" in worker))
|
||||
|
||||
+9
-1
@@ -40,6 +40,11 @@ export interface BuildCtx {
|
||||
* (Obsidian Publish semantics, see util/permalinks.ts). Plain data, so it reaches worker threads.
|
||||
*/
|
||||
permalinks?: Record<string, FullSlug>
|
||||
/**
|
||||
* Frontmatter aliases: alias slug → the slug of the page that has it (util/aliases.ts).
|
||||
* Plain data, so it reaches worker threads.
|
||||
*/
|
||||
aliases?: Record<string, FullSlug>
|
||||
trie?: FileTrieNode<BuildTimeTrieData>
|
||||
incremental: boolean
|
||||
/**
|
||||
@@ -95,7 +100,9 @@ export type WorkerSerializableBuildCtx = Omit<BuildCtx, "cfg" | "trie">
|
||||
|
||||
/** The plain-data fields of {@link BuildCtx} that worker threads need, each one required. */
|
||||
type WorkerCtxFields = {
|
||||
[K in "buildId" | "argv" | "allSlugs" | "allFiles" | "permalinks" | "incremental"]-?: BuildCtx[K]
|
||||
[
|
||||
K in "buildId" | "argv" | "allSlugs" | "allFiles" | "permalinks" | "aliases" | "incremental"
|
||||
]-?: BuildCtx[K]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,6 +118,7 @@ export function workerCtx(ctx: BuildCtx): WorkerSerializableBuildCtx {
|
||||
allSlugs: ctx.allSlugs,
|
||||
allFiles: ctx.allFiles,
|
||||
permalinks: ctx.permalinks ?? {},
|
||||
aliases: ctx.aliases ?? {},
|
||||
incremental: ctx.incremental,
|
||||
}
|
||||
return { ...fields, virtualPages: [] }
|
||||
|
||||
Reference in new issue
Block a user