mirror of
https://github.com/alrayyes/wiki.git
synced 2025-06-01 03:40:59 +00:00
fix relative path resolution in router and link crawling
This commit is contained in:
parent
232652149a
commit
2f6747b166
44 changed files with 160 additions and 106 deletions
17
quartz/util/ctx.ts
Normal file
17
quartz/util/ctx.ts
Normal file
|
@ -0,0 +1,17 @@
|
|||
import { QuartzConfig } from "../cfg"
|
||||
import { ServerSlug } from "./path"
|
||||
|
||||
export interface Argv {
|
||||
directory: string
|
||||
verbose: boolean
|
||||
output: string
|
||||
serve: boolean
|
||||
port: number
|
||||
concurrency?: number
|
||||
}
|
||||
|
||||
export interface BuildCtx {
|
||||
argv: Argv
|
||||
cfg: QuartzConfig
|
||||
allSlugs: ServerSlug[]
|
||||
}
|
22
quartz/util/glob.ts
Normal file
22
quartz/util/glob.ts
Normal file
|
@ -0,0 +1,22 @@
|
|||
import path from "path"
|
||||
import { FilePath } from "./path"
|
||||
import { globby } from "globby"
|
||||
|
||||
export function toPosixPath(fp: string): string {
|
||||
return fp.split(path.sep).join("/")
|
||||
}
|
||||
|
||||
export async function glob(
|
||||
pattern: string,
|
||||
cwd: string,
|
||||
ignorePatterns: string[],
|
||||
): Promise<FilePath[]> {
|
||||
const fps = (
|
||||
await globby(pattern, {
|
||||
cwd,
|
||||
ignore: ignorePatterns,
|
||||
gitignore: true,
|
||||
})
|
||||
).map(toPosixPath)
|
||||
return fps as FilePath[]
|
||||
}
|
28
quartz/util/log.ts
Normal file
28
quartz/util/log.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
import { Spinner } from "cli-spinner"
|
||||
|
||||
export class QuartzLogger {
|
||||
verbose: boolean
|
||||
spinner: Spinner | undefined
|
||||
constructor(verbose: boolean) {
|
||||
this.verbose = verbose
|
||||
}
|
||||
|
||||
start(text: string) {
|
||||
if (this.verbose) {
|
||||
console.log(text)
|
||||
} else {
|
||||
this.spinner = new Spinner(`%s ${text}`)
|
||||
this.spinner.setSpinnerString(18)
|
||||
this.spinner.start()
|
||||
}
|
||||
}
|
||||
|
||||
end(text?: string) {
|
||||
if (!this.verbose) {
|
||||
this.spinner!.stop(true)
|
||||
}
|
||||
if (text) {
|
||||
console.log(text)
|
||||
}
|
||||
}
|
||||
}
|
291
quartz/util/path.test.ts
Normal file
291
quartz/util/path.test.ts
Normal file
|
@ -0,0 +1,291 @@
|
|||
import test, { describe } from "node:test"
|
||||
import * as path from "./path"
|
||||
import assert from "node:assert"
|
||||
import { CanonicalSlug, ServerSlug, TransformOptions } from "./path"
|
||||
|
||||
describe("typeguards", () => {
|
||||
test("isClientSlug", () => {
|
||||
assert(path.isClientSlug("http://example.com"))
|
||||
assert(path.isClientSlug("http://example.com/index"))
|
||||
assert(path.isClientSlug("http://example.com/index.html"))
|
||||
assert(path.isClientSlug("http://example.com/"))
|
||||
assert(path.isClientSlug("https://example.com"))
|
||||
assert(path.isClientSlug("https://example.com/abc/def"))
|
||||
assert(path.isClientSlug("https://example.com/abc/def/"))
|
||||
assert(path.isClientSlug("https://example.com/abc/def#cool"))
|
||||
assert(path.isClientSlug("https://example.com/abc/def?field=1&another=2"))
|
||||
assert(path.isClientSlug("https://example.com/abc/def?field=1&another=2#cool"))
|
||||
assert(path.isClientSlug("https://example.com/abc/def.html?field=1&another=2#cool"))
|
||||
|
||||
assert(!path.isClientSlug("./"))
|
||||
assert(!path.isClientSlug(""))
|
||||
assert(!path.isClientSlug("ipfs://example.com"))
|
||||
assert(!path.isClientSlug("http"))
|
||||
assert(!path.isClientSlug("https"))
|
||||
})
|
||||
|
||||
test("isCanonicalSlug", () => {
|
||||
assert(path.isCanonicalSlug(""))
|
||||
assert(path.isCanonicalSlug("abc"))
|
||||
assert(path.isCanonicalSlug("notindex"))
|
||||
assert(path.isCanonicalSlug("notindex/def"))
|
||||
|
||||
assert(!path.isCanonicalSlug("//"))
|
||||
assert(!path.isCanonicalSlug("index"))
|
||||
assert(!path.isCanonicalSlug("https://example.com"))
|
||||
assert(!path.isCanonicalSlug("/abc"))
|
||||
assert(!path.isCanonicalSlug("abc/"))
|
||||
assert(!path.isCanonicalSlug("abc/index"))
|
||||
assert(!path.isCanonicalSlug("abc#anchor"))
|
||||
assert(!path.isCanonicalSlug("abc?query=1"))
|
||||
assert(!path.isCanonicalSlug("index.md"))
|
||||
assert(!path.isCanonicalSlug("index.html"))
|
||||
})
|
||||
|
||||
test("isRelativeURL", () => {
|
||||
assert(path.isRelativeURL("."))
|
||||
assert(path.isRelativeURL(".."))
|
||||
assert(path.isRelativeURL("./abc/def"))
|
||||
assert(path.isRelativeURL("./abc/def#an-anchor"))
|
||||
assert(path.isRelativeURL("./abc/def?query=1#an-anchor"))
|
||||
assert(path.isRelativeURL("../abc/def"))
|
||||
|
||||
assert(!path.isRelativeURL("abc"))
|
||||
assert(!path.isRelativeURL("/abc/def"))
|
||||
assert(!path.isRelativeURL(""))
|
||||
assert(!path.isRelativeURL("./abc/def.html"))
|
||||
assert(!path.isRelativeURL("./abc/def.md"))
|
||||
})
|
||||
|
||||
test("isServerSlug", () => {
|
||||
assert(path.isServerSlug("index"))
|
||||
assert(path.isServerSlug("abc/def"))
|
||||
|
||||
assert(!path.isServerSlug("."))
|
||||
assert(!path.isServerSlug("./abc/def"))
|
||||
assert(!path.isServerSlug("../abc/def"))
|
||||
assert(!path.isServerSlug("index.html"))
|
||||
assert(!path.isServerSlug("abc/def.html"))
|
||||
assert(!path.isServerSlug("abc/def#anchor"))
|
||||
assert(!path.isServerSlug("abc/def?query=1"))
|
||||
assert(!path.isServerSlug("note with spaces"))
|
||||
})
|
||||
|
||||
test("isFilePath", () => {
|
||||
assert(path.isFilePath("content/index.md"))
|
||||
assert(path.isFilePath("content/test.png"))
|
||||
assert(!path.isFilePath("../test.pdf"))
|
||||
assert(!path.isFilePath("content/test"))
|
||||
assert(!path.isFilePath("./content/test"))
|
||||
})
|
||||
})
|
||||
|
||||
describe("transforms", () => {
|
||||
function asserts<Inp, Out>(
|
||||
pairs: [string, string][],
|
||||
transform: (inp: Inp) => Out,
|
||||
checkPre: (x: any) => x is Inp,
|
||||
checkPost: (x: any) => x is Out,
|
||||
) {
|
||||
for (const [inp, expected] of pairs) {
|
||||
assert(checkPre(inp), `${inp} wasn't the expected input type`)
|
||||
const actual = transform(inp)
|
||||
assert.strictEqual(
|
||||
actual,
|
||||
expected,
|
||||
`after transforming ${inp}, '${actual}' was not '${expected}'`,
|
||||
)
|
||||
assert(checkPost(actual), `${actual} wasn't the expected output type`)
|
||||
}
|
||||
}
|
||||
|
||||
test("canonicalizeServer", () => {
|
||||
asserts(
|
||||
[
|
||||
["index", ""],
|
||||
["abc/index", "abc"],
|
||||
["abc/def", "abc/def"],
|
||||
],
|
||||
path.canonicalizeServer,
|
||||
path.isServerSlug,
|
||||
path.isCanonicalSlug,
|
||||
)
|
||||
})
|
||||
|
||||
test("canonicalizeClient", () => {
|
||||
asserts(
|
||||
[
|
||||
["http://localhost:3000", ""],
|
||||
["http://localhost:3000/index", ""],
|
||||
["http://localhost:3000/test", "test"],
|
||||
["http://example.com", ""],
|
||||
["http://example.com/index", ""],
|
||||
["http://example.com/index.html", ""],
|
||||
["http://example.com/", ""],
|
||||
["https://example.com", ""],
|
||||
["https://example.com/abc/def", "abc/def"],
|
||||
["https://example.com/abc/def/", "abc/def"],
|
||||
["https://example.com/abc/def#cool", "abc/def"],
|
||||
["https://example.com/abc/def?field=1&another=2", "abc/def"],
|
||||
["https://example.com/abc/def?field=1&another=2#cool", "abc/def"],
|
||||
["https://example.com/abc/def.html?field=1&another=2#cool", "abc/def"],
|
||||
],
|
||||
path.canonicalizeClient,
|
||||
path.isClientSlug,
|
||||
path.isCanonicalSlug,
|
||||
)
|
||||
})
|
||||
|
||||
test("slugifyFilePath", () => {
|
||||
asserts(
|
||||
[
|
||||
["content/index.md", "content/index"],
|
||||
["content/_index.md", "content/index"],
|
||||
["/content/index.md", "content/index"],
|
||||
["content/cool.png", "content/cool"],
|
||||
["index.md", "index"],
|
||||
["test.mp4", "test"],
|
||||
["note with spaces.md", "note-with-spaces"],
|
||||
],
|
||||
path.slugifyFilePath,
|
||||
path.isFilePath,
|
||||
path.isServerSlug,
|
||||
)
|
||||
})
|
||||
|
||||
test("transformInternalLink", () => {
|
||||
asserts(
|
||||
[
|
||||
["", "."],
|
||||
[".", "."],
|
||||
["./", "./"],
|
||||
["./index", "./"],
|
||||
["./index.html", "./"],
|
||||
["./index.md", "./"],
|
||||
["content", "./content"],
|
||||
["content/test.md", "./content/test"],
|
||||
["./content/test.md", "./content/test"],
|
||||
["../content/test.md", "../content/test"],
|
||||
["tags/", "./tags/"],
|
||||
["/tags/", "./tags/"],
|
||||
["content/with spaces", "./content/with-spaces"],
|
||||
["content/with spaces/index", "./content/with-spaces/"],
|
||||
["content/with spaces#and Anchor!", "./content/with-spaces#and-anchor"],
|
||||
],
|
||||
path.transformInternalLink,
|
||||
(_x: string): _x is string => true,
|
||||
path.isRelativeURL,
|
||||
)
|
||||
})
|
||||
|
||||
test("pathToRoot", () => {
|
||||
asserts(
|
||||
[
|
||||
["", "."],
|
||||
["abc", ".."],
|
||||
["abc/def", "../.."],
|
||||
],
|
||||
path.pathToRoot,
|
||||
path.isCanonicalSlug,
|
||||
path.isRelativeURL,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("link strategies", () => {
|
||||
const allSlugs = ["a/b/c", "a/b/d", "a/b/index", "e/f", "e/g/h", "index"] as ServerSlug[]
|
||||
|
||||
describe("absolute", () => {
|
||||
const opts: TransformOptions = {
|
||||
strategy: "absolute",
|
||||
allSlugs,
|
||||
}
|
||||
|
||||
test("from a/b/c", () => {
|
||||
const cur = "a/b/c" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/d", opts), "../../../a/b/d")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/index", opts), "../../../a/b")
|
||||
assert.strictEqual(path.transformLink(cur, "e/f", opts), "../../../e/f")
|
||||
assert.strictEqual(path.transformLink(cur, "e/g/h", opts), "../../../e/g/h")
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), "../../..")
|
||||
assert.strictEqual(path.transformLink(cur, "index#abc", opts), "../../../#abc")
|
||||
assert.strictEqual(path.transformLink(cur, "tag/test", opts), "../../../tag/test")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/c#test", opts), "../../../a/b/c#test")
|
||||
})
|
||||
|
||||
test("from a/b/index", () => {
|
||||
const cur = "a/b" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/d", opts), "../../a/b/d")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b", opts), "../../a/b")
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), "../..")
|
||||
})
|
||||
|
||||
test("from index", () => {
|
||||
const cur = "" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), ".")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/c", opts), "./a/b/c")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/index", opts), "./a/b")
|
||||
})
|
||||
})
|
||||
|
||||
describe("shortest", () => {
|
||||
const opts: TransformOptions = {
|
||||
strategy: "shortest",
|
||||
allSlugs,
|
||||
}
|
||||
|
||||
test("from a/b/c", () => {
|
||||
const cur = "a/b/c" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "d", opts), "../../../a/b/d")
|
||||
assert.strictEqual(path.transformLink(cur, "h", opts), "../../../e/g/h")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/index", opts), "../../../a/b")
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), "../../..")
|
||||
})
|
||||
|
||||
test("from a/b/index", () => {
|
||||
const cur = "a/b" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "d", opts), "../../a/b/d")
|
||||
assert.strictEqual(path.transformLink(cur, "h", opts), "../../e/g/h")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/index", opts), "../../a/b")
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), "../..")
|
||||
})
|
||||
|
||||
test("from index", () => {
|
||||
const cur = "" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "d", opts), "./a/b/d")
|
||||
assert.strictEqual(path.transformLink(cur, "h", opts), "./e/g/h")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/index", opts), "./a/b")
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), ".")
|
||||
})
|
||||
})
|
||||
|
||||
describe("relative", () => {
|
||||
const opts: TransformOptions = {
|
||||
strategy: "relative",
|
||||
allSlugs,
|
||||
}
|
||||
|
||||
test("from a/b/c", () => {
|
||||
const cur = "a/b/c" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "d", opts), "./d")
|
||||
assert.strictEqual(path.transformLink(cur, "index", opts), "./")
|
||||
assert.strictEqual(path.transformLink(cur, "../../index", opts), "../../")
|
||||
assert.strictEqual(path.transformLink(cur, "../../", opts), "../../")
|
||||
assert.strictEqual(path.transformLink(cur, "../../e/g/h", opts), "../../e/g/h")
|
||||
})
|
||||
|
||||
test("from a/b/index", () => {
|
||||
const cur = "a/b" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "../../index", opts), "../../")
|
||||
assert.strictEqual(path.transformLink(cur, "../../", opts), "../../")
|
||||
assert.strictEqual(path.transformLink(cur, "../../e/g/h", opts), "../../e/g/h")
|
||||
assert.strictEqual(path.transformLink(cur, "c", opts), "./c")
|
||||
})
|
||||
|
||||
test("from index", () => {
|
||||
const cur = "" as CanonicalSlug
|
||||
assert.strictEqual(path.transformLink(cur, "e/g/h", opts), "./e/g/h")
|
||||
assert.strictEqual(path.transformLink(cur, "a/b/index", opts), "./a/b/")
|
||||
})
|
||||
})
|
||||
})
|
297
quartz/util/path.ts
Normal file
297
quartz/util/path.ts
Normal file
|
@ -0,0 +1,297 @@
|
|||
import { slug } from "github-slugger"
|
||||
// this file must be isomorphic so it can't use node libs (e.g. path)
|
||||
|
||||
// Quartz Paths
|
||||
// Things in boxes are not actual types but rather sources which these types can be acquired from
|
||||
//
|
||||
// ┌────────────┐
|
||||
// ┌───────────┤ Browser ├────────────┐
|
||||
// │ └────────────┘ │
|
||||
// │ │
|
||||
// ▼ ▼
|
||||
// ┌────────┐ ┌─────────────┐
|
||||
// ┌───────────────────┤ Window │ │ LinkElement │
|
||||
// │ └────┬───┘ └──────┬──────┘
|
||||
// │ │ │
|
||||
// │ getClientSlug() │ .href │
|
||||
// │ ▼ ▼
|
||||
// │
|
||||
// │ Client Slug ┌───► Relative URL
|
||||
// getCanonicalSlug() │ https://test.ca/note/abc#anchor?query=123 │ ../note/def#anchor
|
||||
// │ │
|
||||
// │ canonicalizeClient() │ │ ▲ ▲
|
||||
// │ ▼ │ │ │
|
||||
// │ pathToRoot() │ │ │
|
||||
// └───────────────► Canonical Slug ────────────────┘ │ │
|
||||
// note/abc │ │
|
||||
// ──────────────────────────┘ │
|
||||
// ▲ resolveRelative() │
|
||||
// canonicalizeServer() │ │
|
||||
// │
|
||||
// HTML File Server Slug │
|
||||
// note/abc/index.html ◄───────────── note/abc/index │
|
||||
// │
|
||||
// ▲ ┌────────┴────────┐
|
||||
// slugifyFilePath() │ transformLink() │ │
|
||||
// │ │ │
|
||||
// ┌─────────┴──────────┐ ┌─────┴─────┐ ┌────────┴──────┐
|
||||
// │ File Path │ │ Wikilinks │ │ Markdown Link │
|
||||
// │ note/abc/index.md │ └───────────┘ └───────────────┘
|
||||
// └────────────────────┘ ▲ ▲
|
||||
// ▲ │ │
|
||||
// │ ┌─────────┐ │ │
|
||||
// └────────────┤ MD File ├─────┴─────────────────┘
|
||||
// └─────────┘
|
||||
|
||||
export const QUARTZ = "quartz"
|
||||
|
||||
/// Utility type to simulate nominal types in TypeScript
|
||||
type SlugLike<T> = string & { __brand: T }
|
||||
|
||||
/** Client-side slug, usually obtained through `window.location` */
|
||||
export type ClientSlug = SlugLike<"client">
|
||||
export function isClientSlug(s: string): s is ClientSlug {
|
||||
const res = /^https?:\/\/.+/.test(s)
|
||||
return res
|
||||
}
|
||||
|
||||
/** Canonical slug, should be used whenever you need to refer to the location of a file/note.
|
||||
* On the client, this is normally stored in `document.body.dataset.slug`
|
||||
*/
|
||||
export type CanonicalSlug = SlugLike<"canonical">
|
||||
export function isCanonicalSlug(s: string): s is CanonicalSlug {
|
||||
const validStart = !(s.startsWith(".") || s.startsWith("/"))
|
||||
const validEnding = !(s.endsWith("/") || s.endsWith("/index") || s === "index")
|
||||
return validStart && !_containsForbiddenCharacters(s) && validEnding && !_hasFileExtension(s)
|
||||
}
|
||||
|
||||
/** A relative link, can be found on `href`s but can also be constructed for
|
||||
* client-side navigation (e.g. search and graph)
|
||||
*/
|
||||
export type RelativeURL = SlugLike<"relative">
|
||||
export function isRelativeURL(s: string): s is RelativeURL {
|
||||
const validStart = /^\.{1,2}/.test(s)
|
||||
const validEnding = !(s.endsWith("/index") || s === "index")
|
||||
return validStart && validEnding && !_hasFileExtension(s)
|
||||
}
|
||||
|
||||
/** A server side slug. This is what Quartz uses to emit files so uses index suffixes */
|
||||
export type ServerSlug = SlugLike<"server">
|
||||
export function isServerSlug(s: string): s is ServerSlug {
|
||||
const validStart = !(s.startsWith(".") || s.startsWith("/"))
|
||||
const validEnding = !s.endsWith("/")
|
||||
return validStart && validEnding && !_containsForbiddenCharacters(s) && !_hasFileExtension(s)
|
||||
}
|
||||
|
||||
/** The real file path to a file on disk */
|
||||
export type FilePath = SlugLike<"filepath">
|
||||
export function isFilePath(s: string): s is FilePath {
|
||||
const validStart = !s.startsWith(".")
|
||||
return validStart && _hasFileExtension(s)
|
||||
}
|
||||
|
||||
export function getClientSlug(window: Window): ClientSlug {
|
||||
const res = window.location.href as ClientSlug
|
||||
return res
|
||||
}
|
||||
|
||||
export function getCanonicalSlug(window: Window): CanonicalSlug {
|
||||
const res = window.document.body.dataset.slug! as CanonicalSlug
|
||||
return res
|
||||
}
|
||||
|
||||
export function canonicalizeClient(slug: ClientSlug): CanonicalSlug {
|
||||
const { pathname } = new URL(slug)
|
||||
let fp = pathname.slice(1)
|
||||
fp = fp.replace(new RegExp(_getFileExtension(fp) + "$"), "")
|
||||
const res = _canonicalize(fp) as CanonicalSlug
|
||||
return res
|
||||
}
|
||||
|
||||
export function canonicalizeServer(slug: ServerSlug): CanonicalSlug {
|
||||
let fp = slug as string
|
||||
const res = _canonicalize(fp) as CanonicalSlug
|
||||
return res
|
||||
}
|
||||
|
||||
export function slugifyFilePath(fp: FilePath): ServerSlug {
|
||||
fp = _stripSlashes(fp) as FilePath
|
||||
const withoutFileExt = fp.replace(new RegExp(_getFileExtension(fp) + "$"), "")
|
||||
let slug = withoutFileExt
|
||||
.split("/")
|
||||
.map((segment) => segment.replace(/\s/g, "-")) // slugify all segments
|
||||
.join("/") // always use / as sep
|
||||
.replace(/\/$/, "") // remove trailing slash
|
||||
|
||||
// treat _index as index
|
||||
if (_endsWith(slug, "_index")) {
|
||||
slug = slug.replace(/_index$/, "index")
|
||||
}
|
||||
|
||||
return slug as ServerSlug
|
||||
}
|
||||
|
||||
export function transformInternalLink(link: string): RelativeURL {
|
||||
let [fplike, anchor] = splitAnchor(decodeURI(link))
|
||||
|
||||
const folderPath =
|
||||
fplike.endsWith("index") ||
|
||||
fplike.endsWith("index.md") ||
|
||||
fplike.endsWith("index.html") ||
|
||||
fplike.endsWith("/")
|
||||
let segments = fplike.split("/").filter((x) => x.length > 0)
|
||||
let prefix = segments.filter(_isRelativeSegment).join("/")
|
||||
let fp = segments.filter((seg) => !_isRelativeSegment(seg)).join("/")
|
||||
|
||||
// implicit markdown
|
||||
if (!_hasFileExtension(fp)) {
|
||||
fp += ".md"
|
||||
}
|
||||
|
||||
fp = canonicalizeServer(slugifyFilePath(fp as FilePath))
|
||||
const joined = joinSegments(_stripSlashes(prefix), _stripSlashes(fp))
|
||||
const trail = folderPath ? "/" : ""
|
||||
const res = (_addRelativeToStart(joined) + anchor + trail) as RelativeURL
|
||||
return res
|
||||
}
|
||||
|
||||
// resolve /a/b/c to ../../..
|
||||
export function pathToRoot(slug: CanonicalSlug): RelativeURL {
|
||||
let rootPath = slug
|
||||
.split("/")
|
||||
.filter((x) => x !== "")
|
||||
.map((_) => "..")
|
||||
.join("/")
|
||||
|
||||
const res = _addRelativeToStart(rootPath) as RelativeURL
|
||||
return res
|
||||
}
|
||||
|
||||
export function resolveRelative(current: CanonicalSlug, target: CanonicalSlug): RelativeURL {
|
||||
const res = joinSegments(pathToRoot(current), target) as RelativeURL
|
||||
return res
|
||||
}
|
||||
|
||||
export function splitAnchor(link: string): [string, string] {
|
||||
let [fp, anchor] = link.split("#", 2)
|
||||
anchor = anchor === undefined ? "" : "#" + slugAnchor(anchor)
|
||||
return [fp, anchor]
|
||||
}
|
||||
|
||||
export function slugAnchor(anchor: string) {
|
||||
return slug(anchor)
|
||||
}
|
||||
|
||||
export function slugTag(tag: string) {
|
||||
return tag
|
||||
.split("/")
|
||||
.map((tagSegment) => slug(tagSegment))
|
||||
.join("/")
|
||||
}
|
||||
|
||||
export function joinSegments(...args: string[]): string {
|
||||
return args.filter((segment) => segment !== "").join("/")
|
||||
}
|
||||
|
||||
export function getAllSegmentPrefixes(tags: string): string[] {
|
||||
const segments = tags.split("/")
|
||||
const results: string[] = []
|
||||
for (let i = 0; i < segments.length; i++) {
|
||||
results.push(segments.slice(0, i + 1).join("/"))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
export interface TransformOptions {
|
||||
strategy: "absolute" | "relative" | "shortest"
|
||||
allSlugs: ServerSlug[]
|
||||
}
|
||||
|
||||
export function transformLink(
|
||||
src: CanonicalSlug,
|
||||
target: string,
|
||||
opts: TransformOptions,
|
||||
): RelativeURL {
|
||||
let targetSlug: string = transformInternalLink(target)
|
||||
|
||||
if (opts.strategy === "relative") {
|
||||
return _addRelativeToStart(targetSlug) as RelativeURL
|
||||
} else {
|
||||
targetSlug = _stripSlashes(targetSlug.slice(".".length))
|
||||
let [targetCanonical, targetAnchor] = splitAnchor(targetSlug)
|
||||
|
||||
if (opts.strategy === "shortest") {
|
||||
// if the file name is unique, then it's just the filename
|
||||
const matchingFileNames = opts.allSlugs.filter((slug) => {
|
||||
const parts = slug.split("/")
|
||||
const fileName = parts.at(-1)
|
||||
return targetCanonical === fileName
|
||||
})
|
||||
|
||||
// only match, just use it
|
||||
if (matchingFileNames.length === 1) {
|
||||
const targetSlug = canonicalizeServer(matchingFileNames[0])
|
||||
return (resolveRelative(src, targetSlug) + targetAnchor) as RelativeURL
|
||||
}
|
||||
}
|
||||
|
||||
// if it's not unique, then it's the absolute path from the vault root
|
||||
return joinSegments(pathToRoot(src), targetSlug) as RelativeURL
|
||||
}
|
||||
}
|
||||
|
||||
function _canonicalize(fp: string): string {
|
||||
fp = _trimSuffix(fp, "index")
|
||||
return _stripSlashes(fp)
|
||||
}
|
||||
|
||||
function _endsWith(s: string, suffix: string): boolean {
|
||||
return s === suffix || s.endsWith("/" + suffix)
|
||||
}
|
||||
|
||||
function _trimSuffix(s: string, suffix: string): string {
|
||||
if (_endsWith(s, suffix)) {
|
||||
s = s.slice(0, -suffix.length)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
function _containsForbiddenCharacters(s: string): boolean {
|
||||
return s.includes(" ") || s.includes("#") || s.includes("?")
|
||||
}
|
||||
|
||||
function _hasFileExtension(s: string): boolean {
|
||||
return _getFileExtension(s) !== undefined
|
||||
}
|
||||
|
||||
function _getFileExtension(s: string): string | undefined {
|
||||
return s.match(/\.[A-Za-z0-9]+$/)?.[0]
|
||||
}
|
||||
|
||||
function _isRelativeSegment(s: string): boolean {
|
||||
return /^\.{0,2}$/.test(s)
|
||||
}
|
||||
|
||||
export function _stripSlashes(s: string): string {
|
||||
if (s.startsWith("/")) {
|
||||
s = s.substring(1)
|
||||
}
|
||||
|
||||
if (s.endsWith("/")) {
|
||||
s = s.slice(0, -1)
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
function _addRelativeToStart(s: string): string {
|
||||
if (s === "") {
|
||||
s = "."
|
||||
}
|
||||
|
||||
if (!s.startsWith(".")) {
|
||||
s = joinSegments(".", s)
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
19
quartz/util/perf.ts
Normal file
19
quartz/util/perf.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import chalk from "chalk"
|
||||
import pretty from "pretty-time"
|
||||
|
||||
export class PerfTimer {
|
||||
evts: { [key: string]: [number, number] }
|
||||
|
||||
constructor() {
|
||||
this.evts = {}
|
||||
this.addEvent("start")
|
||||
}
|
||||
|
||||
addEvent(evtName: string) {
|
||||
this.evts[evtName] = process.hrtime()
|
||||
}
|
||||
|
||||
timeSince(evtName?: string): string {
|
||||
return chalk.yellow(pretty(process.hrtime(this.evts[evtName ?? "start"])))
|
||||
}
|
||||
}
|
39
quartz/util/resources.tsx
Normal file
39
quartz/util/resources.tsx
Normal file
|
@ -0,0 +1,39 @@
|
|||
import { randomUUID } from "crypto"
|
||||
import { JSX } from "preact/jsx-runtime"
|
||||
|
||||
export type JSResource = {
|
||||
loadTime: "beforeDOMReady" | "afterDOMReady"
|
||||
moduleType?: "module"
|
||||
spaPreserve?: boolean
|
||||
} & (
|
||||
| {
|
||||
src: string
|
||||
contentType: "external"
|
||||
}
|
||||
| {
|
||||
script: string
|
||||
contentType: "inline"
|
||||
}
|
||||
)
|
||||
|
||||
export function JSResourceToScriptElement(resource: JSResource, preserve?: boolean): JSX.Element {
|
||||
const scriptType = resource.moduleType ?? "application/javascript"
|
||||
const spaPreserve = preserve ?? resource.spaPreserve
|
||||
if (resource.contentType === "external") {
|
||||
return (
|
||||
<script key={resource.src} src={resource.src} type={scriptType} spa-preserve={spaPreserve} />
|
||||
)
|
||||
} else {
|
||||
const content = resource.script
|
||||
return (
|
||||
<script key={randomUUID()} type={scriptType} spa-preserve={spaPreserve}>
|
||||
{content}
|
||||
</script>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export interface StaticResources {
|
||||
css: string[]
|
||||
js: JSResource[]
|
||||
}
|
18
quartz/util/sourcemap.ts
Normal file
18
quartz/util/sourcemap.ts
Normal file
|
@ -0,0 +1,18 @@
|
|||
import fs from "fs"
|
||||
import sourceMapSupport from "source-map-support"
|
||||
import { fileURLToPath } from "url"
|
||||
|
||||
export const options: sourceMapSupport.Options = {
|
||||
// source map hack to get around query param
|
||||
// import cache busting
|
||||
retrieveSourceMap(source) {
|
||||
if (source.includes(".quartz-cache")) {
|
||||
let realSource = fileURLToPath(source.split("?", 2)[0] + ".map")
|
||||
return {
|
||||
map: fs.readFileSync(realSource, "utf8"),
|
||||
}
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
},
|
||||
}
|
63
quartz/util/theme.ts
Normal file
63
quartz/util/theme.ts
Normal file
|
@ -0,0 +1,63 @@
|
|||
export interface ColorScheme {
|
||||
light: string
|
||||
lightgray: string
|
||||
gray: string
|
||||
darkgray: string
|
||||
dark: string
|
||||
secondary: string
|
||||
tertiary: string
|
||||
highlight: string
|
||||
}
|
||||
|
||||
export interface Theme {
|
||||
typography: {
|
||||
header: string
|
||||
body: string
|
||||
code: string
|
||||
}
|
||||
colors: {
|
||||
lightMode: ColorScheme
|
||||
darkMode: ColorScheme
|
||||
}
|
||||
}
|
||||
|
||||
const DEFAULT_SANS_SERIF =
|
||||
'-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif'
|
||||
const DEFAULT_MONO = "ui-monospace, SFMono-Regular, SF Mono, Menlo, monospace"
|
||||
|
||||
export function googleFontHref(theme: Theme) {
|
||||
const { code, header, body } = theme.typography
|
||||
return `https://fonts.googleapis.com/css2?family=${code}&family=${header}:wght@400;700&family=${body}:ital,wght@0,400;0,600;1,400;1,600&display=swap`
|
||||
}
|
||||
|
||||
export function joinStyles(theme: Theme, ...stylesheet: string[]) {
|
||||
return `
|
||||
${stylesheet.join("\n\n")}
|
||||
|
||||
:root {
|
||||
--light: ${theme.colors.lightMode.light};
|
||||
--lightgray: ${theme.colors.lightMode.lightgray};
|
||||
--gray: ${theme.colors.lightMode.gray};
|
||||
--darkgray: ${theme.colors.lightMode.darkgray};
|
||||
--dark: ${theme.colors.lightMode.dark};
|
||||
--secondary: ${theme.colors.lightMode.secondary};
|
||||
--tertiary: ${theme.colors.lightMode.tertiary};
|
||||
--highlight: ${theme.colors.lightMode.highlight};
|
||||
|
||||
--headerFont: ${theme.typography.header}, ${DEFAULT_SANS_SERIF};
|
||||
--bodyFont: ${theme.typography.body}, ${DEFAULT_SANS_SERIF};
|
||||
--codeFont: ${theme.typography.code}, ${DEFAULT_MONO};
|
||||
}
|
||||
|
||||
:root[saved-theme="dark"] {
|
||||
--light: ${theme.colors.darkMode.light};
|
||||
--lightgray: ${theme.colors.darkMode.lightgray};
|
||||
--gray: ${theme.colors.darkMode.gray};
|
||||
--darkgray: ${theme.colors.darkMode.darkgray};
|
||||
--dark: ${theme.colors.darkMode.dark};
|
||||
--secondary: ${theme.colors.darkMode.secondary};
|
||||
--tertiary: ${theme.colors.darkMode.tertiary};
|
||||
--highlight: ${theme.colors.darkMode.highlight};
|
||||
}
|
||||
`
|
||||
}
|
47
quartz/util/trace.ts
Normal file
47
quartz/util/trace.ts
Normal file
|
@ -0,0 +1,47 @@
|
|||
import chalk from "chalk"
|
||||
import process from "process"
|
||||
import { isMainThread } from "workerpool"
|
||||
|
||||
const rootFile = /.*at file:/
|
||||
export function trace(msg: string, err: Error) {
|
||||
const stack = err.stack
|
||||
|
||||
const lines: string[] = []
|
||||
|
||||
lines.push("")
|
||||
lines.push(
|
||||
"\n" +
|
||||
chalk.bgRed.black.bold(" ERROR ") +
|
||||
"\n" +
|
||||
chalk.red(` ${msg}`) +
|
||||
(err.message.length > 0 ? `: ${err.message}` : ""),
|
||||
)
|
||||
|
||||
if (!stack) {
|
||||
return
|
||||
}
|
||||
|
||||
let reachedEndOfLegibleTrace = false
|
||||
for (const line of stack.split("\n").slice(1)) {
|
||||
if (reachedEndOfLegibleTrace) {
|
||||
break
|
||||
}
|
||||
|
||||
if (!line.includes("node_modules")) {
|
||||
lines.push(` ${line}`)
|
||||
if (rootFile.test(line)) {
|
||||
reachedEndOfLegibleTrace = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const traceMsg = lines.join("\n")
|
||||
if (!isMainThread) {
|
||||
// gather lines and throw
|
||||
throw new Error(traceMsg)
|
||||
} else {
|
||||
// print and exit
|
||||
console.error(traceMsg)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue