@sixb/app 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +172 -0
- package/dist/agents.d.ts +6 -0
- package/dist/agents.d.ts.map +1 -0
- package/dist/agents.js +26 -0
- package/dist/agents.js.map +10 -0
- package/dist/build.d.ts +21 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/codegen.d.ts +43 -0
- package/dist/codegen.d.ts.map +1 -0
- package/dist/createCustomApp.d.ts +43 -0
- package/dist/createCustomApp.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1464 -0
- package/dist/index.js.map +18 -0
- package/dist/manifest.d.ts +3 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/metadata.d.ts +29 -0
- package/dist/metadata.d.ts.map +1 -0
- package/dist/runtime.d.ts +12 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/scanner.d.ts +19 -0
- package/dist/scanner.d.ts.map +1 -0
- package/dist/styles.d.ts +33 -0
- package/dist/styles.d.ts.map +1 -0
- package/dist/tailwind.d.ts +62 -0
- package/dist/tailwind.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/package.json +74 -0
- package/src/agents.ts +23 -0
- package/src/build.ts +105 -0
- package/src/codegen.ts +587 -0
- package/src/createCustomApp.ts +770 -0
- package/src/index.ts +15 -0
- package/src/manifest.ts +29 -0
- package/src/metadata.ts +206 -0
- package/src/runtime.ts +16 -0
- package/src/scanner.ts +81 -0
- package/src/styles.ts +83 -0
- package/src/tailwind.ts +195 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export {
|
|
2
|
+
type CreateCustomAppOptions,
|
|
3
|
+
type CustomAppBuildOptions,
|
|
4
|
+
type CustomAppDevOptions,
|
|
5
|
+
type CustomAppDevServer,
|
|
6
|
+
type CustomAppInstance,
|
|
7
|
+
type CustomAppStartOptions,
|
|
8
|
+
createCustomApp,
|
|
9
|
+
} from "./createCustomApp"
|
|
10
|
+
export type { AppMetadata } from "./metadata"
|
|
11
|
+
export {
|
|
12
|
+
createTailwindCssCompiler,
|
|
13
|
+
type TailwindCssCompiler,
|
|
14
|
+
type TailwindCssCompilerOptions,
|
|
15
|
+
} from "./tailwind"
|
package/src/manifest.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ResolvedAppMetadata, ResolvedManifestIcon } from "./metadata"
|
|
2
|
+
|
|
3
|
+
interface CustomAppManifest {
|
|
4
|
+
readonly id: "/"
|
|
5
|
+
readonly name: string
|
|
6
|
+
readonly description?: string
|
|
7
|
+
readonly start_url: "/"
|
|
8
|
+
readonly scope: "/"
|
|
9
|
+
readonly display: "standalone"
|
|
10
|
+
readonly theme_color: string
|
|
11
|
+
readonly background_color: string
|
|
12
|
+
readonly icons?: readonly ResolvedManifestIcon[]
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function renderAppManifest(metadata: ResolvedAppMetadata): string {
|
|
16
|
+
const manifest: CustomAppManifest = {
|
|
17
|
+
id: "/",
|
|
18
|
+
name: metadata.title,
|
|
19
|
+
...(metadata.description ? { description: metadata.description } : {}),
|
|
20
|
+
start_url: "/",
|
|
21
|
+
scope: "/",
|
|
22
|
+
display: "standalone",
|
|
23
|
+
theme_color: metadata.themeColor,
|
|
24
|
+
background_color: metadata.backgroundColor,
|
|
25
|
+
...(metadata.icons.length > 0 ? { icons: metadata.icons } : {}),
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return `${JSON.stringify(manifest, null, 2)}\n`
|
|
29
|
+
}
|
package/src/metadata.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { readFile, stat } from "node:fs/promises"
|
|
3
|
+
import { createRequire } from "node:module"
|
|
4
|
+
import { extname, join } from "node:path"
|
|
5
|
+
import { pathToFileURL } from "node:url"
|
|
6
|
+
|
|
7
|
+
export interface AppMetadata {
|
|
8
|
+
title?: string
|
|
9
|
+
description?: string
|
|
10
|
+
favicon?: string
|
|
11
|
+
themeColor?: string
|
|
12
|
+
backgroundColor?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface ResolvedManifestIcon {
|
|
16
|
+
readonly src: string
|
|
17
|
+
readonly sizes?: string
|
|
18
|
+
readonly type?: string
|
|
19
|
+
readonly purpose?: "any" | "maskable"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ResolvedAppMetadata {
|
|
23
|
+
readonly title: string
|
|
24
|
+
readonly description?: string
|
|
25
|
+
readonly favicon?: string
|
|
26
|
+
readonly themeColor: string
|
|
27
|
+
readonly backgroundColor: string
|
|
28
|
+
readonly appleTouchIcon?: string
|
|
29
|
+
readonly icons: readonly ResolvedManifestIcon[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ResolveAppMetadataOptions {
|
|
33
|
+
readonly layoutPath: string
|
|
34
|
+
readonly publicDir: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const metadataRequire = createRequire(import.meta.url)
|
|
38
|
+
|
|
39
|
+
const metadataFields = [
|
|
40
|
+
"title",
|
|
41
|
+
"description",
|
|
42
|
+
"favicon",
|
|
43
|
+
"themeColor",
|
|
44
|
+
"backgroundColor",
|
|
45
|
+
] as const satisfies readonly (keyof AppMetadata)[]
|
|
46
|
+
|
|
47
|
+
/** Loads, validates, defaults, and resolves all custom-app identity in one place. */
|
|
48
|
+
export async function resolveAppMetadata(
|
|
49
|
+
options: ResolveAppMetadataOptions
|
|
50
|
+
): Promise<ResolvedAppMetadata> {
|
|
51
|
+
const configured = await loadConfiguredMetadata(options.layoutPath)
|
|
52
|
+
validateMetadata(configured, options.layoutPath)
|
|
53
|
+
|
|
54
|
+
const conventionalFaviconPath = join(options.publicDir, "favicon.svg")
|
|
55
|
+
const favicon =
|
|
56
|
+
configured.favicon ?? ((await fileExists(conventionalFaviconPath)) ? "/favicon.svg" : undefined)
|
|
57
|
+
const themeColor = configured.themeColor ?? configured.backgroundColor ?? "#ffffff"
|
|
58
|
+
const backgroundColor = configured.backgroundColor ?? themeColor
|
|
59
|
+
const icons: ResolvedManifestIcon[] = []
|
|
60
|
+
|
|
61
|
+
if (await fileExists(join(options.publicDir, "icon-192.png"))) {
|
|
62
|
+
icons.push({
|
|
63
|
+
src: "/icon-192.png",
|
|
64
|
+
sizes: "192x192",
|
|
65
|
+
type: "image/png",
|
|
66
|
+
purpose: "any",
|
|
67
|
+
})
|
|
68
|
+
}
|
|
69
|
+
if (await fileExists(join(options.publicDir, "icon-512.png"))) {
|
|
70
|
+
icons.push({
|
|
71
|
+
src: "/icon-512.png",
|
|
72
|
+
sizes: "512x512",
|
|
73
|
+
type: "image/png",
|
|
74
|
+
purpose: "any",
|
|
75
|
+
})
|
|
76
|
+
}
|
|
77
|
+
if (await fileExists(join(options.publicDir, "icon-maskable-512.png"))) {
|
|
78
|
+
icons.push({
|
|
79
|
+
src: "/icon-maskable-512.png",
|
|
80
|
+
sizes: "512x512",
|
|
81
|
+
type: "image/png",
|
|
82
|
+
purpose: "maskable",
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const hasStandardIcon = icons.some((icon) => icon.purpose === "any")
|
|
87
|
+
if (!hasStandardIcon && favicon) {
|
|
88
|
+
const type = inferImageMimeType(favicon)
|
|
89
|
+
if (type) {
|
|
90
|
+
icons.push({
|
|
91
|
+
src: favicon,
|
|
92
|
+
...(type === "image/svg+xml" ? { sizes: "any" } : {}),
|
|
93
|
+
type,
|
|
94
|
+
purpose: "any",
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
title: configured.title ?? "Sixb",
|
|
101
|
+
...(configured.description ? { description: configured.description } : {}),
|
|
102
|
+
...(favicon ? { favicon } : {}),
|
|
103
|
+
themeColor,
|
|
104
|
+
backgroundColor,
|
|
105
|
+
...((await fileExists(join(options.publicDir, "apple-touch-icon.png")))
|
|
106
|
+
? { appleTouchIcon: "/apple-touch-icon.png" }
|
|
107
|
+
: {}),
|
|
108
|
+
icons,
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function loadConfiguredMetadata(layoutPath: string): Promise<AppMetadata> {
|
|
113
|
+
if (!(await fileExists(layoutPath))) {
|
|
114
|
+
return {}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
const sourceHash = createHash("sha256")
|
|
119
|
+
.update(await readFile(layoutPath))
|
|
120
|
+
.digest("hex")
|
|
121
|
+
const url = pathToFileURL(layoutPath)
|
|
122
|
+
// Bun currently canonicalizes file-URL query strings in its module cache.
|
|
123
|
+
// Explicit invalidation makes the source fingerprint a reliable dev cache
|
|
124
|
+
// buster while retaining a normal file URL and relative import behavior.
|
|
125
|
+
delete metadataRequire.cache[metadataRequire.resolve(layoutPath)]
|
|
126
|
+
url.searchParams.set("sixb-metadata", sourceHash)
|
|
127
|
+
const layoutModule = (await import(url.href)) as { readonly metadata?: unknown }
|
|
128
|
+
|
|
129
|
+
if (layoutModule.metadata === undefined) {
|
|
130
|
+
return {}
|
|
131
|
+
}
|
|
132
|
+
if (
|
|
133
|
+
typeof layoutModule.metadata !== "object" ||
|
|
134
|
+
layoutModule.metadata === null ||
|
|
135
|
+
Array.isArray(layoutModule.metadata)
|
|
136
|
+
) {
|
|
137
|
+
throw metadataError(layoutPath, "the named metadata export must be an object")
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return layoutModule.metadata as AppMetadata
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error instanceof Error && error.message.startsWith("[SixbCustomApp]")) {
|
|
143
|
+
throw error
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
147
|
+
throw new Error(
|
|
148
|
+
`[SixbCustomApp] Could not load metadata from ${layoutPath}: ${detail}. ` +
|
|
149
|
+
"App metadata is build-time configuration, so app/layout.tsx must be import-safe in Bun " +
|
|
150
|
+
"and must not access window or document at module scope."
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function validateMetadata(metadata: AppMetadata, layoutPath: string): void {
|
|
156
|
+
for (const field of metadataFields) {
|
|
157
|
+
const value = metadata[field]
|
|
158
|
+
if (value !== undefined && (typeof value !== "string" || value.trim().length === 0)) {
|
|
159
|
+
throw metadataError(layoutPath, `metadata.${field} must be a non-empty string when provided`)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function metadataError(layoutPath: string, detail: string): Error {
|
|
165
|
+
return new Error(`[SixbCustomApp] Invalid app metadata in ${layoutPath}: ${detail}`)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function inferImageMimeType(url: string): string | undefined {
|
|
169
|
+
if (url.startsWith("data:")) {
|
|
170
|
+
const match = /^data:(image\/[a-z0-9.+-]+)/i.exec(url)
|
|
171
|
+
return match?.[1]?.toLowerCase()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let pathname = url
|
|
175
|
+
try {
|
|
176
|
+
pathname = new URL(url, "https://sixb.invalid").pathname
|
|
177
|
+
} catch {
|
|
178
|
+
// Fall back to extension parsing on the configured value.
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
switch (extname(pathname).toLowerCase()) {
|
|
182
|
+
case ".svg":
|
|
183
|
+
return "image/svg+xml"
|
|
184
|
+
case ".png":
|
|
185
|
+
return "image/png"
|
|
186
|
+
case ".ico":
|
|
187
|
+
return "image/x-icon"
|
|
188
|
+
case ".jpg":
|
|
189
|
+
case ".jpeg":
|
|
190
|
+
return "image/jpeg"
|
|
191
|
+
case ".webp":
|
|
192
|
+
return "image/webp"
|
|
193
|
+
case ".avif":
|
|
194
|
+
return "image/avif"
|
|
195
|
+
default:
|
|
196
|
+
return undefined
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function fileExists(path: string): Promise<boolean> {
|
|
201
|
+
try {
|
|
202
|
+
return (await stat(path)).isFile()
|
|
203
|
+
} catch {
|
|
204
|
+
return false
|
|
205
|
+
}
|
|
206
|
+
}
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AuthSessionAudience } from "@sixb/core"
|
|
2
|
+
|
|
3
|
+
export interface CustomAppRuntimeConfig {
|
|
4
|
+
readonly api: {
|
|
5
|
+
readonly baseUrl: string
|
|
6
|
+
}
|
|
7
|
+
readonly auth: {
|
|
8
|
+
readonly audience: AuthSessionAudience
|
|
9
|
+
readonly enabled: boolean
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function renderCustomAppRuntimeScript(config: CustomAppRuntimeConfig): string {
|
|
14
|
+
const safeConfig = JSON.stringify(config).replaceAll("<", "\\u003c")
|
|
15
|
+
return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`
|
|
16
|
+
}
|
package/src/scanner.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises"
|
|
2
|
+
import { join, relative } from "node:path"
|
|
3
|
+
|
|
4
|
+
export interface PageRoute {
|
|
5
|
+
/** React Router path, e.g. "/" or "/remote/:id" */
|
|
6
|
+
path: string
|
|
7
|
+
/** Absolute file path */
|
|
8
|
+
filePath: string
|
|
9
|
+
/** Relative path from the app directory, e.g. "remote/[id]/page.tsx" */
|
|
10
|
+
relativePath: string
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Recursively scans an `app/` directory for `page.tsx`/`page.ts` files and
|
|
15
|
+
* converts them to React Router route paths.
|
|
16
|
+
*
|
|
17
|
+
* - `app/page.tsx` -> `/`
|
|
18
|
+
* - `app/about/page.tsx` -> `/about`
|
|
19
|
+
* - `app/remote/[id]/page.tsx` -> `/remote/:id`
|
|
20
|
+
* - Files starting with `_` are skipped.
|
|
21
|
+
*/
|
|
22
|
+
export async function scanPages(appDir: string): Promise<PageRoute[]> {
|
|
23
|
+
const routes: PageRoute[] = []
|
|
24
|
+
await walkDir(appDir, appDir, routes)
|
|
25
|
+
routes.sort((a, b) => a.path.localeCompare(b.path))
|
|
26
|
+
return routes
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function walkDir(dir: string, appDir: string, routes: PageRoute[]): Promise<void> {
|
|
30
|
+
let entries: import("node:fs").Dirent[]
|
|
31
|
+
try {
|
|
32
|
+
entries = (await readdir(dir, { withFileTypes: true })) as import("node:fs").Dirent[]
|
|
33
|
+
} catch {
|
|
34
|
+
return
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
for (const entry of entries) {
|
|
38
|
+
const name = String(entry.name)
|
|
39
|
+
if (name.startsWith("_")) continue
|
|
40
|
+
|
|
41
|
+
const fullPath = join(dir, name)
|
|
42
|
+
|
|
43
|
+
if (entry.isDirectory()) {
|
|
44
|
+
await walkDir(fullPath, appDir, routes)
|
|
45
|
+
continue
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (!entry.isFile()) continue
|
|
49
|
+
const isPageModule = name === "page.tsx" || name === "page.ts"
|
|
50
|
+
if (!isPageModule) continue
|
|
51
|
+
|
|
52
|
+
const relativePath = relative(appDir, fullPath)
|
|
53
|
+
const routePath = filePathToRoutePath(relativePath)
|
|
54
|
+
|
|
55
|
+
routes.push({
|
|
56
|
+
path: routePath,
|
|
57
|
+
filePath: fullPath,
|
|
58
|
+
relativePath,
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function filePathToRoutePath(filePath: string): string {
|
|
64
|
+
// Remove extension
|
|
65
|
+
let route = filePath.replace(/\.(tsx|ts)$/, "")
|
|
66
|
+
|
|
67
|
+
// Normalize path separators
|
|
68
|
+
route = route.split("\\").join("/")
|
|
69
|
+
|
|
70
|
+
// Convert [param] to :param
|
|
71
|
+
route = route.replace(/\[([^\]]+)\]/g, ":$1")
|
|
72
|
+
|
|
73
|
+
// Remove trailing /page
|
|
74
|
+
if (route === "page") return "/"
|
|
75
|
+
route = route.replace(/\/page$/, "")
|
|
76
|
+
|
|
77
|
+
// Ensure leading slash
|
|
78
|
+
if (!route.startsWith("/")) route = `/${route}`
|
|
79
|
+
|
|
80
|
+
return route
|
|
81
|
+
}
|
package/src/styles.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { join } from "node:path"
|
|
3
|
+
import { resolveTailwindCliEntry } from "./tailwind"
|
|
4
|
+
|
|
5
|
+
export type CustomAppStylesheet =
|
|
6
|
+
/** No `app/globals.css` — the app ships no framework-managed stylesheet. */
|
|
7
|
+
| { readonly kind: "none" }
|
|
8
|
+
/** Plain handwritten CSS — bundled as-is, exactly as before. */
|
|
9
|
+
| { readonly kind: "static"; readonly path: string }
|
|
10
|
+
/** Tailwind source — compiled to `outputPath` before bundling. */
|
|
11
|
+
| { readonly kind: "tailwind"; readonly sourcePath: string; readonly outputPath: string }
|
|
12
|
+
|
|
13
|
+
export interface ResolveCustomAppStylesheetInput {
|
|
14
|
+
readonly appDir: string
|
|
15
|
+
readonly generatedDir: string
|
|
16
|
+
readonly rootDir: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Decides how `app/globals.css` participates in the build.
|
|
21
|
+
*
|
|
22
|
+
* `globals.css` is treated as Tailwind *source* when it uses Tailwind at-rules
|
|
23
|
+
* (`@source`, `@theme`, ...) or imports a package stylesheet such as
|
|
24
|
+
* `@sixb/ui/globals.css` — those need the Tailwind pipeline before they are
|
|
25
|
+
* shippable. Plain CSS keeps the existing pass-through behavior, so apps that
|
|
26
|
+
* never opted into Tailwind are unaffected.
|
|
27
|
+
*/
|
|
28
|
+
export async function resolveCustomAppStylesheet(
|
|
29
|
+
input: ResolveCustomAppStylesheetInput
|
|
30
|
+
): Promise<CustomAppStylesheet> {
|
|
31
|
+
const sourcePath = join(input.appDir, "globals.css")
|
|
32
|
+
|
|
33
|
+
let css: string
|
|
34
|
+
try {
|
|
35
|
+
css = await readFile(sourcePath, "utf-8")
|
|
36
|
+
} catch {
|
|
37
|
+
return { kind: "none" }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (!usesTailwind(css)) {
|
|
41
|
+
return { kind: "static", path: sourcePath }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (!resolveTailwindCliEntry(input.rootDir)) {
|
|
45
|
+
throw new Error(
|
|
46
|
+
"[SixbCustomApp] app/globals.css uses Tailwind features but '@tailwindcss/cli' is not installed. Install it with: bun add tailwindcss @tailwindcss/cli"
|
|
47
|
+
)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
kind: "tailwind",
|
|
52
|
+
sourcePath,
|
|
53
|
+
outputPath: join(input.generatedDir, "app.css"),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const TAILWIND_AT_RULES =
|
|
58
|
+
/@(?:tailwind|source|theme|plugin|config|utility|custom-variant|variant|apply)\b/
|
|
59
|
+
|
|
60
|
+
export function usesTailwind(css: string): boolean {
|
|
61
|
+
const stripped = css.replace(/\/\*[\s\S]*?\*\//g, "")
|
|
62
|
+
|
|
63
|
+
if (TAILWIND_AT_RULES.test(stripped)) {
|
|
64
|
+
return true
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// A bare-specifier @import (e.g. `@import "tailwindcss"` or
|
|
68
|
+
// `@import "@sixb/ui/globals.css"`) pulls in package CSS that the browser
|
|
69
|
+
// bundler would inline without processing its Tailwind directives.
|
|
70
|
+
for (const match of stripped.matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)) {
|
|
71
|
+
const specifier = match[1]
|
|
72
|
+
if (
|
|
73
|
+
!specifier.startsWith(".") &&
|
|
74
|
+
!specifier.startsWith("/") &&
|
|
75
|
+
!specifier.startsWith("#") &&
|
|
76
|
+
!/^(?:https?:|data:)/.test(specifier)
|
|
77
|
+
) {
|
|
78
|
+
return true
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return false
|
|
83
|
+
}
|
package/src/tailwind.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises"
|
|
2
|
+
import { dirname, join } from "node:path"
|
|
3
|
+
|
|
4
|
+
export interface TailwindCssCompilerOptions {
|
|
5
|
+
/** Tailwind source stylesheet. */
|
|
6
|
+
inputPath: string
|
|
7
|
+
/** Compiled CSS output path. */
|
|
8
|
+
outputPath: string
|
|
9
|
+
/**
|
|
10
|
+
* Working directory for the Tailwind CLI. Tailwind v4's automatic source
|
|
11
|
+
* detection scans from here, so keep it scoped to the directory that owns the
|
|
12
|
+
* styles (e.g. `app/`) — never a repo root that may contain `vendor/` or
|
|
13
|
+
* `node_modules/` siblings.
|
|
14
|
+
*/
|
|
15
|
+
cwd?: string
|
|
16
|
+
/**
|
|
17
|
+
* Directory whose dependency tree is used to resolve `@tailwindcss/cli`.
|
|
18
|
+
* Defaults to `cwd`. Pass the project root so the project's own Tailwind
|
|
19
|
+
* version wins.
|
|
20
|
+
*/
|
|
21
|
+
resolveFrom?: string
|
|
22
|
+
/** Prefix for error messages, e.g. `[SixbAtlas]`. */
|
|
23
|
+
label?: string
|
|
24
|
+
/** Minify the compiled CSS. Off by default; bundlers usually minify later. */
|
|
25
|
+
minify?: boolean
|
|
26
|
+
/** Debounce for `schedule()` rebuilds, in milliseconds. */
|
|
27
|
+
debounceMs?: number
|
|
28
|
+
/**
|
|
29
|
+
* Upper bound on one Tailwind build, in milliseconds. Defaults to 60s.
|
|
30
|
+
*
|
|
31
|
+
* A bound on a hang, not a performance budget: a wedged CLI otherwise held `sixb dev` open
|
|
32
|
+
* forever, and `stop()` waited on it.
|
|
33
|
+
*/
|
|
34
|
+
timeoutMs?: number
|
|
35
|
+
/** Called when a `schedule()`d rebuild fails. Defaults to `console.error`. */
|
|
36
|
+
onError?: (error: Error) => void
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface TailwindCssCompiler {
|
|
40
|
+
/**
|
|
41
|
+
* Compiles the stylesheet. Builds are serialized: a call made while another
|
|
42
|
+
* build is running starts a fresh build after it, so the output always
|
|
43
|
+
* reflects the sources as of the call. Throws with a labeled, actionable
|
|
44
|
+
* error when the CLI is missing or compilation fails.
|
|
45
|
+
*/
|
|
46
|
+
compile(): Promise<void>
|
|
47
|
+
/**
|
|
48
|
+
* Debounced `compile()` for watch flows. Coalesces bursts of file events;
|
|
49
|
+
* errors go to `onError` instead of throwing.
|
|
50
|
+
*/
|
|
51
|
+
schedule(): void
|
|
52
|
+
/** Cancels pending rebuilds and waits for any in-flight build to settle. */
|
|
53
|
+
stop(): Promise<void>
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Resolves the Tailwind v4 CLI entry point from a directory's dependency tree.
|
|
58
|
+
* Returns null when `@tailwindcss/cli` is not installed there.
|
|
59
|
+
*/
|
|
60
|
+
export function resolveTailwindCliEntry(resolveFrom: string): string | null {
|
|
61
|
+
try {
|
|
62
|
+
const packageJsonPath = Bun.resolveSync("@tailwindcss/cli/package.json", resolveFrom)
|
|
63
|
+
return join(dirname(packageJsonPath), "dist", "index.mjs")
|
|
64
|
+
} catch {
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Shared Tailwind v4 CSS build pipeline used by the built-in UI (Atlas) and
|
|
71
|
+
* custom apps. Owns CLI resolution, source-detection scoping,
|
|
72
|
+
* debounced/queued rebuilds, error formatting, and watch lifecycle cleanup.
|
|
73
|
+
*/
|
|
74
|
+
export function createTailwindCssCompiler(
|
|
75
|
+
options: TailwindCssCompilerOptions
|
|
76
|
+
): TailwindCssCompiler {
|
|
77
|
+
const cwd = options.cwd ?? dirname(options.inputPath)
|
|
78
|
+
const resolveFrom = options.resolveFrom ?? cwd
|
|
79
|
+
const label = options.label ?? "[SixbTailwind]"
|
|
80
|
+
const debounceMs = options.debounceMs ?? 50
|
|
81
|
+
const timeoutMs = options.timeoutMs ?? 60_000
|
|
82
|
+
const onError = options.onError ?? ((error: Error) => console.error(`${label} ${error.message}`))
|
|
83
|
+
|
|
84
|
+
let chain: Promise<void> = Promise.resolve()
|
|
85
|
+
let timer: ReturnType<typeof setTimeout> | null = null
|
|
86
|
+
let stopped = false
|
|
87
|
+
let activeProcess: { kill: (signal?: number | NodeJS.Signals) => void } | null = null
|
|
88
|
+
|
|
89
|
+
async function runCompile(): Promise<void> {
|
|
90
|
+
// `compile()` queues this behind the current chain, so a `stop()` can land before the
|
|
91
|
+
// child is ever spawned. Without this the build started anyway and there was nothing
|
|
92
|
+
// for `stop()` to kill, so shutdown waited out the full timeout.
|
|
93
|
+
if (stopped) return
|
|
94
|
+
|
|
95
|
+
const cliEntry = resolveTailwindCliEntry(resolveFrom)
|
|
96
|
+
if (!cliEntry) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
`${label} Tailwind CSS build requires '@tailwindcss/cli'. Install it with: bun add tailwindcss @tailwindcss/cli`
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
await mkdir(dirname(options.outputPath), { recursive: true })
|
|
103
|
+
// The only await before the spawn, so the only other window a `stop()` can land in.
|
|
104
|
+
if (stopped) return
|
|
105
|
+
|
|
106
|
+
const args = [process.execPath, cliEntry, "-i", options.inputPath, "-o", options.outputPath]
|
|
107
|
+
if (options.minify) {
|
|
108
|
+
args.push("--minify")
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const proc = Bun.spawn(args, {
|
|
112
|
+
cwd,
|
|
113
|
+
stdout: "ignore",
|
|
114
|
+
stderr: "pipe",
|
|
115
|
+
})
|
|
116
|
+
activeProcess = proc
|
|
117
|
+
|
|
118
|
+
// Start draining stderr while the child runs rather than after it exits. Bun buffers
|
|
119
|
+
// this pipe today, so reading afterwards does not block the child — measured, not
|
|
120
|
+
// assumed — but that is Bun's choice and not something this code should depend on. The
|
|
121
|
+
// catch keeps a stream torn down by `kill()` from surfacing as an unhandled rejection.
|
|
122
|
+
const stderr = new Response(proc.stderr).text().catch(() => "")
|
|
123
|
+
|
|
124
|
+
let timeout: ReturnType<typeof setTimeout> | undefined
|
|
125
|
+
const timedOut = new Promise<"timeout">((resolve) => {
|
|
126
|
+
timeout = setTimeout(() => resolve("timeout"), timeoutMs)
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
try {
|
|
130
|
+
const outcome = await Promise.race([proc.exited, timedOut])
|
|
131
|
+
|
|
132
|
+
// `stop()` kills the child on purpose. Reporting that as a build failure would put
|
|
133
|
+
// an error in the log for every shutdown that happened to catch a rebuild.
|
|
134
|
+
if (stopped) return
|
|
135
|
+
|
|
136
|
+
if (outcome === "timeout") {
|
|
137
|
+
proc.kill("SIGKILL")
|
|
138
|
+
await proc.exited
|
|
139
|
+
throw new Error(
|
|
140
|
+
`${label} Tailwind CSS build did not finish within ${timeoutMs}ms and was killed. ` +
|
|
141
|
+
`Check ${options.inputPath} and the sources Tailwind scans from ${cwd}.`
|
|
142
|
+
)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (outcome !== 0) {
|
|
146
|
+
throw new Error(`${label} Tailwind CSS build failed: ${(await stderr).trim()}`)
|
|
147
|
+
}
|
|
148
|
+
} finally {
|
|
149
|
+
clearTimeout(timeout)
|
|
150
|
+
activeProcess = null
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function compile(): Promise<void> {
|
|
155
|
+
stopped = false
|
|
156
|
+
const build = chain.then(() => runCompile())
|
|
157
|
+
// The chain itself swallows failures so one bad build doesn't poison every
|
|
158
|
+
// later compile; callers still observe their own build's error.
|
|
159
|
+
chain = build.then(
|
|
160
|
+
() => {},
|
|
161
|
+
() => {}
|
|
162
|
+
)
|
|
163
|
+
return build
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
compile,
|
|
168
|
+
|
|
169
|
+
schedule() {
|
|
170
|
+
if (stopped) return
|
|
171
|
+
if (timer) {
|
|
172
|
+
clearTimeout(timer)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
timer = setTimeout(() => {
|
|
176
|
+
timer = null
|
|
177
|
+
compile().catch((error) => {
|
|
178
|
+
onError(error instanceof Error ? error : new Error(String(error)))
|
|
179
|
+
})
|
|
180
|
+
}, debounceMs)
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
async stop() {
|
|
184
|
+
stopped = true
|
|
185
|
+
if (timer) {
|
|
186
|
+
clearTimeout(timer)
|
|
187
|
+
timer = null
|
|
188
|
+
}
|
|
189
|
+
// Kill rather than wait. A build in flight would otherwise hold shutdown for up to
|
|
190
|
+
// the whole timeout, and the output it is writing is about to be discarded anyway.
|
|
191
|
+
activeProcess?.kill("SIGKILL")
|
|
192
|
+
await chain
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
}
|