Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(html-artifact): extract the workspace HTML publish core into a package (#19356)

Innei08cbe3236bca
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c724bc4c9c6..781caec2bf9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2480,6 +2480,7 @@
"workingPanel.localFile.publish.tooLarge": "This page is too large to publish ({{size}} bytes).",
"workingPanel.localFile.publish.tooMany": "This page references too many local files to publish.",
"workingPanel.localFile.publish.unresolvedLocals": "This page still points at local files that were not packed, so those assets would break after publish.",
+ "workingPanel.localFile.publish.unsupported": "These file types cannot be published and will be skipped: {{list}}",
"workingPanel.localFile.publish.upload_one": "1 larger file will be uploaded with the page.",
"workingPanel.localFile.publish.upload_other": "{{count}} larger files will be uploaded with the page.",
"workingPanel.localFile.publish.uploadingProgress": "Uploading {{completed}} / {{total}} · {{percent}}%",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 5dace004841..45e84fb8ded 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2480,6 +2480,7 @@
"workingPanel.localFile.publish.tooLarge": "此页面过大,无法发布({{size}} 字节)。",
"workingPanel.localFile.publish.tooMany": "此页面引用的本地文件过多,无法发布。",
"workingPanel.localFile.publish.unresolvedLocals": "此页面仍引用未打包的本地文件,发布后这些资源会失效。",
+ "workingPanel.localFile.publish.unsupported": "这些文件类型无法发布,将被跳过:{{list}}",
"workingPanel.localFile.publish.upload_one": "1 个较大的文件会与页面一起上传。",
"workingPanel.localFile.publish.upload_other": "{{count}} 个较大的文件会与页面一起上传。",
"workingPanel.localFile.publish.uploadingProgress": "正在上传 {{completed}} / {{total}} · {{percent}}%",
diff --git a/package.json b/package.json
index c6dcbc26c0c..f204830dbb9 100644
--- a/package.json
+++ b/package.json
@@ -293,6 +293,7 @@
"@lobechat/fetch-sse": "workspace:*",
"@lobechat/file-loaders": "workspace:*",
"@lobechat/heterogeneous-agents": "workspace:*",
+ "@lobechat/html-artifact": "workspace:*",
"@lobechat/llm-generation-tracing": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
"@lobechat/markdown-patch": "workspace:*",
diff --git a/packages/html-artifact/package.json b/packages/html-artifact/package.json
new file mode 100644
index 00000000000..cdfc16c71c7
--- /dev/null
+++ b/packages/html-artifact/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@lobechat/html-artifact",
+ "version": "1.0.0",
+ "private": true,
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "scripts": {
+ "test": "vitest",
+ "test:coverage": "vitest --coverage --silent='passed-only'"
+ },
+ "dependencies": {
+ "@lobechat/const": "workspace:*",
+ "@lobechat/prompts": "workspace:*",
+ "@lobechat/utils": "workspace:*",
+ "es-toolkit": "^1.50.0",
+ "js-sha256": "^0.11.1"
+ }
+}
diff --git a/src/features/Portal/LocalFile/collectHtmlLocalResources.test.ts b/packages/html-artifact/src/collectHtmlLocalResources.test.ts
similarity index 91%
rename from src/features/Portal/LocalFile/collectHtmlLocalResources.test.ts
rename to packages/html-artifact/src/collectHtmlLocalResources.test.ts
index d7bef1217d2..0668f7adccf 100644
--- a/src/features/Portal/LocalFile/collectHtmlLocalResources.test.ts
+++ b/packages/html-artifact/src/collectHtmlLocalResources.test.ts
@@ -1,8 +1,11 @@
import { describe, expect, it } from 'vitest';
-import { extractHtmlTitle } from '@/components/HtmlPreview/htmlTagScanner';
-
-import { collectJsResourceHrefs, collectLocalResourceRefs } from './collectHtmlLocalResources';
+import {
+ collectCssResourceHrefs,
+ collectJsResourceHrefs,
+ collectLocalResourceRefs,
+} from './collectHtmlLocalResources';
+import { extractHtmlTitle } from './htmlTagScanner';
import {
createWorkspaceHtmlArtifactIdentifier,
isPathInsideWorkspace,
@@ -311,4 +314,21 @@ describe('path helpers', () => {
'/tmp/site/index.html',
);
});
+ it('strips css comments without going quadratic on unterminated openers', () => {
+ const css = `
+ @import "kept.css";
+ /* a comment with url("ignored.png") inside */
+ body { background: url("used.png"); }
+ `;
+
+ expect(collectCssResourceHrefs(css)).toEqual(['kept.css', 'used.png']);
+
+ // A sheet of unclosed openers is what makes the lazy regex backtrack; the
+ // scanner must return promptly and treat the first opener as running to EOF.
+ const pathological = `body{background:url("late.png")}${'a/*'.repeat(40_000)}`;
+ const started = Date.now();
+ expect(collectCssResourceHrefs(pathological)).toEqual(['late.png']);
+ expect(Date.now() - started).toBeLessThan(1000);
+ });
+
});
diff --git a/src/features/Portal/LocalFile/collectHtmlLocalResources.ts b/packages/html-artifact/src/collectHtmlLocalResources.ts
similarity index 92%
rename from src/features/Portal/LocalFile/collectHtmlLocalResources.ts
rename to packages/html-artifact/src/collectHtmlLocalResources.ts
index eb280c240e7..e2f653a089c 100644
--- a/src/features/Portal/LocalFile/collectHtmlLocalResources.ts
+++ b/packages/html-artifact/src/collectHtmlLocalResources.ts
@@ -1,6 +1,5 @@
-import { findAttribute, findOpeningTag, findTagEnd } from '@/components/HtmlPreview/htmlTagScanner';
-
-import { getFileExtension } from './Body.helpers';
+import { getFileExtension } from './fileExtension';
+import { findAttribute, findOpeningTag, findTagEnd } from './htmlTagScanner';
import { parentDirectory, resolveLocalResourceHref } from './workspaceHtmlPath';
const ALLOWED_ASSET_EXTENSIONS = new Set([
@@ -142,7 +141,26 @@ const collectTagAttributeHrefs = (tagText: string): string[] => {
return hrefs;
};
-const stripCssComments = (css: string): string => css.replaceAll(/\/\*[\s\S]*?\*\//g, '');
+/**
+ * Scanned rather than matched with `/\*[\s\S]*?\*\//g`: on a stylesheet full of
+ * unterminated `/*` the lazy match restarts from every opener and goes
+ * quadratic, and the CSS reaching here comes from files the user names.
+ */
+const stripCssComments = (css: string): string => {
+ let result = '';
+ let index = 0;
+
+ for (;;) {
+ const start = css.indexOf('/*', index);
+ if (start === -1) return result + css.slice(index);
+
+ result += css.slice(index, start);
+ const end = css.indexOf('*/', start + 2);
+ // An unterminated comment runs to the end of the sheet, as CSS defines it.
+ if (end === -1) return result;
+ index = end + 2;
+ }
+};
const readCssUrlArgument = (source: string, openParenIndex: number): string | undefined => {
let index = openParenIndex + 1;
diff --git a/packages/html-artifact/src/fileExtension.ts b/packages/html-artifact/src/fileExtension.ts
new file mode 100644
index 00000000000..151b9e9781d
--- /dev/null
+++ b/packages/html-artifact/src/fileExtension.ts
@@ -0,0 +1,7 @@
+export const getFileExtension = (filename: string): string => {
+ const base = filename.split('/').at(-1) ?? filename;
+ if (base.startsWith('.') && !base.slice(1).includes('.')) return '';
+ const dotIdx = base.lastIndexOf('.');
+ if (dotIdx < 0) return '';
+ return base.slice(dotIdx + 1);
+};
diff --git a/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.test.ts b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.ts
similarity index 91%
rename from src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.test.ts
rename to packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.ts
index afd057c750b..293c1d28761 100644
--- a/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.test.ts
+++ b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
import { gatherWorkspaceHtmlArtifact } from './gatherWorkspaceHtmlArtifact';
-import type { ReadWorkspaceAssetResult } from './readWorkspaceAsset';
+import type { ReadWorkspaceAssetResult } from './limits';
const textAsset = (text: string, contentType = 'text/plain'): ReadWorkspaceAssetResult => ({
bytes: new TextEncoder().encode(text),
@@ -264,4 +264,22 @@ describe('gatherWorkspaceHtmlArtifact', () => {
'https://cdn.example.com/bg.png',
]);
});
+ it('reports allowlist-rejected references from the html and from nested stylesheets', async () => {
+ const css = '@font-face { src: url("../fonts/brand.fontkit"); }';
+ const files = new Map<string, ReadWorkspaceAssetResult>([
+ ['/project/pages/app.css', textAsset(css, 'text/css')],
+ ]);
+
+ const result = await gatherWorkspaceHtmlArtifact({
+ htmlContent:
+ '<link rel="stylesheet" href="app.css"><link rel="manifest" href="./site.webmanifest">',
+ htmlFilePath: '/project/pages/index.html',
+ readAsset: async (absolutePath) =>
+ files.get(absolutePath) ?? { ok: false, reason: 'missing' },
+ workingDirectory: '/project',
+ });
+
+ expect(result.unsupported).toEqual(['./site.webmanifest', '../fonts/brand.fontkit']);
+ expect(result.missing).toEqual([]);
+ });
});
diff --git a/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.ts b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.ts
similarity index 90%
rename from src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.ts
rename to packages/html-artifact/src/gatherWorkspaceHtmlArtifact.ts
index 155b0ead006..7d0b0923901 100644
--- a/src/features/Portal/LocalFile/gatherWorkspaceHtmlArtifact.ts
+++ b/packages/html-artifact/src/gatherWorkspaceHtmlArtifact.ts
@@ -1,18 +1,18 @@
import { bytesToBase64 } from '@lobechat/utils';
-import { extractHtmlTitle } from '@/components/HtmlPreview/htmlTagScanner';
-
import {
type CollectedLocalResourceRef,
collectLocalResourceRefs,
isCssAssetPath,
isJsAssetPath,
+ type LocalResourceSkipReason,
} from './collectHtmlLocalResources';
+import { extractHtmlTitle } from './htmlTagScanner';
import {
type ReadWorkspaceAssetResult,
WORKSPACE_HTML_ARTIFACT_MAX_FILES,
WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES,
-} from './readWorkspaceAsset';
+} from './limits';
import type { WorkspaceHtmlArtifactFile } from './workspaceHtmlArtifact';
import {
lowestCommonAncestorDirectory,
@@ -32,6 +32,7 @@ export interface GatheredWorkspaceHtmlArtifact {
remotes: string[];
title: string;
totalBytes: number;
+ unsupported: string[];
}
const READ_CONCURRENCY = 5;
@@ -88,20 +89,25 @@ export const gatherWorkspaceHtmlArtifact = async ({
const missing: string[] = [];
const oversized: string[] = [];
const remotes: string[] = [];
+ const unsupported: string[] = [];
const htmlDirectory = parentDirectory(absoluteHtmlPath);
- const addRemotes = (skipped: typeof htmlRefs.skipped) => {
+ const bucketForSkipReason = (reason: LocalResourceSkipReason): string[] | undefined => {
+ if (reason === 'remote') return remotes;
+ if (reason === 'escape') return missing;
+ if (reason === 'extension') return unsupported;
+ return;
+ };
+
+ const collectSkipped = (skipped: typeof htmlRefs.skipped) => {
for (const item of skipped) {
- if (item.reason !== 'remote') continue;
- if (!remotes.includes(item.href)) remotes.push(item.href);
+ const bucket = bucketForSkipReason(item.reason);
+ if (!bucket || bucket.includes(item.href)) continue;
+ bucket.push(item.href);
}
};
- addRemotes(htmlRefs.skipped);
- for (const item of htmlRefs.skipped) {
- if (item.reason !== 'escape') continue;
- if (!missing.includes(item.href)) missing.push(item.href);
- }
+ collectSkipped(htmlRefs.skipped);
const resolvedAssets: Array<{
absolutePath: string;
bytes: Uint8Array;
@@ -184,7 +190,7 @@ export const gatherWorkspaceHtmlArtifact = async ({
sourcePath: walkRef.absolutePath,
workingDirectory,
});
- addRemotes(nested.skipped);
+ collectSkipped(nested.skipped);
for (const ref of nested.refs) {
if (seen.has(ref.absolutePath)) continue;
@@ -237,5 +243,6 @@ export const gatherWorkspaceHtmlArtifact = async ({
remotes,
title: extractHtmlTitle(htmlContent) || filename,
totalBytes,
+ unsupported,
};
};
diff --git a/src/components/HtmlPreview/htmlTagScanner.ts b/packages/html-artifact/src/htmlTagScanner.ts
similarity index 100%
rename from src/components/HtmlPreview/htmlTagScanner.ts
rename to packages/html-artifact/src/htmlTagScanner.ts
diff --git a/packages/html-artifact/src/index.ts b/packages/html-artifact/src/index.ts
new file mode 100644
index 00000000000..fc3bc4eef7b
--- /dev/null
+++ b/packages/html-artifact/src/index.ts
@@ -0,0 +1,9 @@
+export * from './collectHtmlLocalResources';
+export * from './fileExtension';
+export * from './gatherWorkspaceHtmlArtifact';
+export * from './htmlTagScanner';
+export * from './limits';
+export * from './packWorkspaceHtmlDocument';
+export * from './publishWorkspaceHtmlArtifact';
+export * from './workspaceHtmlArtifact';
+export * from './workspaceHtmlPath';
diff --git a/packages/html-artifact/src/limits.ts b/packages/html-artifact/src/limits.ts
new file mode 100644
index 00000000000..0b4fe8a5524
--- /dev/null
+++ b/packages/html-artifact/src/limits.ts
@@ -0,0 +1,47 @@
+import { getMimeType } from '@lobechat/utils';
+
+export const WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES = 50 * 1024 * 1024;
+export const WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
+export const WORKSPACE_HTML_ARTIFACT_MAX_FILES = 64;
+export const WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES = 32 * 1024;
+
+export type ReadWorkspaceAssetFailure = 'missing' | 'oversized' | 'unreadable';
+
+export interface ReadWorkspaceAssetSuccess {
+ bytes: Uint8Array;
+ contentType: string;
+ ok: true;
+ text?: string;
+}
+
+export interface ReadWorkspaceAssetError {
+ ok: false;
+ reason: ReadWorkspaceAssetFailure;
+ sizeBytes?: number;
+}
+
+export type ReadWorkspaceAssetResult = ReadWorkspaceAssetError | ReadWorkspaceAssetSuccess;
+
+const TEXT_CONTENT_TYPES = new Set([
+ 'application/javascript',
+ 'application/json',
+ 'application/xml',
+ 'image/svg+xml',
+ 'text/css',
+ 'text/html',
+ 'text/javascript',
+ 'text/plain',
+]);
+
+export const isTextContentType = (contentType: string): boolean => {
+ const bare = contentType.split(';')[0].trim().toLowerCase();
+ return bare.startsWith('text/') || TEXT_CONTENT_TYPES.has(bare);
+};
+
+export const resolveWorkspaceAssetContentType = (path: string, reported?: string): string => {
+ const guessed = getMimeType(path);
+ if (guessed !== 'application/octet-stream') return guessed;
+
+ const reportedType = reported?.split(';')[0]?.trim();
+ return reportedType || guessed;
+};
diff --git a/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.test.ts b/packages/html-artifact/src/packWorkspaceHtmlDocument.test.ts
similarity index 99%
rename from src/features/Portal/LocalFile/packWorkspaceHtmlDocument.test.ts
rename to packages/html-artifact/src/packWorkspaceHtmlDocument.test.ts
index 2901b2dc338..fadd762518a 100644
--- a/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.test.ts
+++ b/packages/html-artifact/src/packWorkspaceHtmlDocument.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
+import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './limits';
import { packWorkspaceHtmlDocument } from './packWorkspaceHtmlDocument';
-import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './readWorkspaceAsset';
describe('packWorkspaceHtmlDocument', () => {
it('inlines small local css and images as data uris and leaves remotes', () => {
diff --git a/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.ts b/packages/html-artifact/src/packWorkspaceHtmlDocument.ts
similarity index 99%
rename from src/features/Portal/LocalFile/packWorkspaceHtmlDocument.ts
rename to packages/html-artifact/src/packWorkspaceHtmlDocument.ts
index 494a018a720..5e053169a20 100644
--- a/src/features/Portal/LocalFile/packWorkspaceHtmlDocument.ts
+++ b/packages/html-artifact/src/packWorkspaceHtmlDocument.ts
@@ -11,7 +11,7 @@ import {
import {
resolveWorkspaceAssetContentType,
WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES,
-} from './readWorkspaceAsset';
+} from './limits';
import type { WorkspaceHtmlArtifactFile } from './workspaceHtmlArtifact';
import { resolveLocalResourceHref, toWorkspaceRelativePath } from './workspaceHtmlPath';
diff --git a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts b/packages/html-artifact/src/publishWorkspaceHtmlArtifact.test.ts
similarity index 100%
rename from src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.test.ts
rename to packages/html-artifact/src/publishWorkspaceHtmlArtifact.test.ts
diff --git a/packages/html-artifact/src/publishWorkspaceHtmlArtifact.ts b/packages/html-artifact/src/publishWorkspaceHtmlArtifact.ts
new file mode 100644
index 00000000000..4d0743f7a6a
--- /dev/null
+++ b/packages/html-artifact/src/publishWorkspaceHtmlArtifact.ts
@@ -0,0 +1,125 @@
+import { ARTIFACT_TAG } from '@lobechat/const';
+import { escapeXmlAttr } from '@lobechat/prompts';
+
+import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './limits';
+import { hostedPath, packWorkspaceHtmlDocument } from './packWorkspaceHtmlDocument';
+import type {
+ WorkspaceHtmlArtifactFile,
+ WorkspaceHtmlArtifactPublishInput,
+ WorkspaceHtmlArtifactPublishResult,
+} from './workspaceHtmlArtifact';
+
+export const wrapWorkspaceHtmlArtifact = ({
+ html,
+ identifier,
+ title,
+}: {
+ html: string;
+ identifier: string;
+ title: string;
+}): string =>
+ `<${ARTIFACT_TAG} identifier="${escapeXmlAttr(identifier)}" type="text/html" title="${escapeXmlAttr(title)}">\n${html}\n</${ARTIFACT_TAG}>`;
+
+export interface PublishWorkspaceHtmlSiteParams {
+ artifactIdentifier: string;
+ files: WorkspaceHtmlArtifactFile[];
+ html: string;
+ onPhase?: WorkspaceHtmlArtifactPublishInput['onUploadPhase'];
+ onProgress?: WorkspaceHtmlArtifactPublishInput['onUploadProgress'];
+ requestedSlug?: string;
+ signal?: AbortSignal;
+ title?: string;
+ topicId: string;
+}
+
+export const publishWorkspaceHtmlArtifact = async (
+ input: WorkspaceHtmlArtifactPublishInput,
+ deps: {
+ createMessage: (params: {
+ agentId: string;
+ content: string;
+ role: 'assistant';
+ topicId: string;
+ }) => Promise<{ id: string }>;
+ publishArtifact: (params: {
+ artifactIdentifier: string;
+ messageId: string;
+ requestedSlug?: string;
+ topicId: string;
+ }) => Promise<{ id?: string; latestRevisionNumber?: number; publicUrl?: string }>;
+ publishSite?: (
+ params: PublishWorkspaceHtmlSiteParams,
+ ) => Promise<{ id?: string; latestRevisionNumber?: number; publicUrl?: string }>;
+ },
+): Promise<WorkspaceHtmlArtifactPublishResult> => {
+ const packed =
+ input.packed ??
+ (() => {
+ const fresh = packWorkspaceHtmlDocument({
+ entryPath: input.entryPath,
+ files: input.files,
+ });
+ if (fresh.unresolvedHrefs.length > 0) {
+ throw new Error('unresolved-local-assets');
+ }
+ return fresh;
+ })();
+
+ if (
+ packed.sidecars.length > 0 ||
+ new TextEncoder().encode(packed.html).byteLength > WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES
+ ) {
+ if (!deps.publishSite) {
+ throw new Error('unavailable');
+ }
+
+ const deployment = await deps.publishSite({
+ artifactIdentifier: input.identifier,
+ files: packed.sidecars.map((file) => ({
+ ...file,
+ path: hostedPath(file.path),
+ })),
+ html: packed.html,
+ onPhase: input.onUploadPhase,
+ onProgress: input.onUploadProgress,
+ requestedSlug: input.title,
+ signal: input.signal,
+ title: input.title,
+ topicId: input.topicId,
+ });
+
+ return {
+ id: deployment.id,
+ publicUrl: deployment.publicUrl,
+ revision: deployment.latestRevisionNumber,
+ };
+ }
+
+ if (!input.agentId) {
+ throw new Error('unavailable');
+ }
+
+ const message = await deps.createMessage({
+ agentId: input.agentId,
+ content: wrapWorkspaceHtmlArtifact({
+ html: packed.html,
+ identifier: input.identifier,
+ title: input.title,
+ }),
+ role: 'assistant',
+ topicId: input.topicId,
+ });
+
+ const deployment = await deps.publishArtifact({
+ artifactIdentifier: input.identifier,
+ messageId: message.id,
+ requestedSlug: input.title,
+ topicId: input.topicId,
+ });
+
+ return {
+ id: deployment.id,
+ publicUrl: deployment.publicUrl,
+ revision: deployment.latestRevisionNumber,
+ };
+};
diff --git a/packages/html-artifact/src/workspaceHtmlArtifact.ts b/packages/html-artifact/src/workspaceHtmlArtifact.ts
new file mode 100644
index 00000000000..3ee695a4a1e
--- /dev/null
+++ b/packages/html-artifact/src/workspaceHtmlArtifact.ts
@@ -0,0 +1,49 @@
+export interface WorkspaceHtmlArtifactFile {
+ content: string;
+ contentType: string;
+ encoding: 'base64' | 'utf8';
+ path: string;
+}
+
+export interface WorkspaceHtmlArtifactPublishInput {
+ agentId?: string;
+ entryPath: string;
+ files: WorkspaceHtmlArtifactFile[];
+ identifier: string;
+ onUploadPhase?: (phase: 'finalizing' | 'preparing' | 'uploading') => void;
+ onUploadProgress?: (progress: {
+ completedFiles: number;
+ loadedBytes: number;
+ totalBytes: number;
+ totalFiles: number;
+ }) => void;
+ packed?: { html: string; sidecars: WorkspaceHtmlArtifactFile[] };
+ signal?: AbortSignal;
+ title: string;
+ topicId: string;
+}
+
+export interface WorkspaceHtmlArtifactExisting {
+ id?: string;
+ identifier: string;
+ publicUrl?: string;
+ revision?: number;
+ status?: string;
+}
+
+export interface WorkspaceHtmlArtifactPublishResult {
+ id?: string;
+ publicUrl?: string;
+ revision?: number;
+}
+
+export interface WorkspaceHtmlArtifactPublisher {
+ available: boolean;
+ getExisting: (input: {
+ identifier: string;
+ topicId: string;
+ }) => Promise<WorkspaceHtmlArtifactExisting | null>;
+ publish: (
+ input: WorkspaceHtmlArtifactPublishInput,
+ ) => Promise<WorkspaceHtmlArtifactPublishResult>;
+}
diff --git a/packages/html-artifact/src/workspaceHtmlPath.ts b/packages/html-artifact/src/workspaceHtmlPath.ts
new file mode 100644
index 00000000000..1196a18c584
--- /dev/null
+++ b/packages/html-artifact/src/workspaceHtmlPath.ts
@@ -0,0 +1,213 @@
+import { sha256 } from 'js-sha256';
+
+const toSlashPath = (filePath: string): string => filePath.replaceAll('\\', '/');
+
+const fromSlashPath = (filePath: string, sourcePath: string): string => {
+ const usesWindowsSeparator = sourcePath.includes('\\') && !sourcePath.includes('/');
+ return usesWindowsSeparator ? filePath.replaceAll('/', '\\') : filePath;
+};
+
+const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
+
+const DARWIN_PRIVATE_ROOTS = ['/tmp', '/var', '/etc'] as const;
+
+const canonicalizeWorkspacePath = (filePath: string): string => {
+ const slashPath = stripTrailingSlash(toSlashPath(filePath));
+
+ for (const root of DARWIN_PRIVATE_ROOTS) {
+ const privateRoot = `/private${root}`;
+ if (slashPath === privateRoot || slashPath.startsWith(`${privateRoot}/`)) {
+ return slashPath.slice('/private'.length);
+ }
+ }
+
+ return slashPath;
+};
+
+const decodePathSegment = (segment: string): string => {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+};
+
+const splitResourceHref = (href: string): string => {
+ const queryIndex = href.indexOf('?');
+ const hashIndex = href.indexOf('#');
+ const suffixIndex = [queryIndex, hashIndex]
+ .filter((index) => index >= 0)
+ .sort((a, b) => a - b)[0];
+ return (suffixIndex === undefined ? href : href.slice(0, suffixIndex)).trim();
+};
+
+const normalizeSlashPath = (
+ filePath: string,
+ { preserveLeadingDoubleSlash = false }: { preserveLeadingDoubleSlash?: boolean } = {},
+): string => {
+ const leadingEmptySegmentLimit = preserveLeadingDoubleSlash && filePath.startsWith('//') ? 2 : 1;
+ const normalizedSegments: string[] = [];
+
+ for (const segment of filePath.split('/')) {
+ if (!segment || segment === '.') {
+ if (
+ segment === '' &&
+ normalizedSegments.length < leadingEmptySegmentLimit &&
+ normalizedSegments.every((item) => item === '')
+ ) {
+ normalizedSegments.push('');
+ }
+ continue;
+ }
+
+ if (segment === '..') {
+ if (normalizedSegments.length > 1) normalizedSegments.pop();
+ continue;
+ }
+
+ normalizedSegments.push(segment);
+ }
+
+ return normalizedSegments.join('/') || '/';
+};
+
+const parentDirectory = (filePath: string): string => {
+ const slashPath = toSlashPath(filePath);
+ const isUncPath = slashPath.startsWith('//');
+ const lastSeparatorIndex = slashPath.lastIndexOf('/');
+ if (lastSeparatorIndex < 0) return '';
+ if (slashPath.startsWith('/') && lastSeparatorIndex === 0) return '/';
+ const directory = slashPath.slice(0, lastSeparatorIndex);
+ return fromSlashPath(isUncPath && directory === '' ? '//' : directory, filePath);
+};
+
+export const isPathInsideWorkspace = (targetPath: string, workingDirectory: string): boolean => {
+ const target = canonicalizeWorkspacePath(targetPath);
+ const root = canonicalizeWorkspacePath(workingDirectory);
+ return target === root || target.startsWith(`${root}/`);
+};
+
+export const toWorkspaceAbsolutePath = (filePath: string, workingDirectory: string): string => {
+ const slashPath = toSlashPath(filePath);
+ if (isPathInsideWorkspace(filePath, workingDirectory)) {
+ return fromSlashPath(slashPath, workingDirectory);
+ }
+
+ const isAbsolute = slashPath.startsWith('/') || /^[a-zA-Z]:/u.test(filePath);
+ if (isAbsolute) return filePath;
+
+ const root = stripTrailingSlash(toSlashPath(workingDirectory));
+ return fromSlashPath(normalizeSlashPath(`${root}/${slashPath}`), workingDirectory);
+};
+
+export const toWorkspaceRelativePath = (absolutePath: string, workingDirectory: string): string => {
+ const target = canonicalizeWorkspacePath(absolutePath);
+ const root = canonicalizeWorkspacePath(workingDirectory);
+ if (target === root) return '';
+ if (target.startsWith(`${root}/`)) return target.slice(root.length + 1);
+ return stripTrailingSlash(toSlashPath(absolutePath)).split('/').at(-1) ?? absolutePath;
+};
+
+export const lowestCommonAncestorDirectory = (
+ absolutePaths: string[],
+ workingDirectory: string,
+): string => {
+ if (absolutePaths.length === 0) return workingDirectory;
+
+ const relativeDirs = absolutePaths.map((absolutePath) => {
+ const relativePath = toWorkspaceRelativePath(absolutePath, workingDirectory);
+ const segments = relativePath.split('/').filter(Boolean);
+ return segments.slice(0, -1);
+ });
+
+ const [first, ...rest] = relativeDirs;
+ const common: string[] = [];
+
+ for (const [index, segment] of first.entries()) {
+ if (rest.every((dirs) => dirs[index] === segment)) {
+ common.push(segment);
+ continue;
+ }
+ break;
+ }
+
+ if (common.length === 0) return workingDirectory;
+
+ const slashRoot = `${stripTrailingSlash(toSlashPath(workingDirectory))}/${common.join('/')}`;
+ return fromSlashPath(slashRoot, workingDirectory);
+};
+
+const joinPath = (basePath: string, segments: string[], sourcePath: string): string => {
+ const slashBase = toSlashPath(basePath);
+ const isUncPath = slashBase.startsWith('//');
+ const resolved = normalizeSlashPath(
+ slashBase ? [slashBase, ...segments].join('/') : segments.join('/'),
+ {
+ preserveLeadingDoubleSlash: isUncPath,
+ },
+ );
+ return fromSlashPath(resolved, sourcePath);
+};
+
+const resolveAgainstDirectory = (directory: string, href: string, sourcePath: string): string => {
+ const segments = href.split(/[\\/]+/).map(decodePathSegment);
+ return joinPath(directory, segments, sourcePath);
+};
+
+export const resolveLocalResourceHref = ({
+ href,
+ rootDirectory,
+ sourcePath,
+ workingDirectory,
+}: {
+ href: string;
+ rootDirectory?: string;
+ sourcePath: string;
+ workingDirectory: string;
+}): { absolutePath?: string; href: string; kind: 'empty' | 'escape' | 'remote' | 'resolved' } => {
+ const assetPath = splitResourceHref(href);
+ if (!assetPath || assetPath === '#' || assetPath.startsWith('#')) {
+ return { href, kind: 'empty' };
+ }
+
+ if (/^[a-z][a-z\d+.-]*:/i.test(assetPath) || assetPath.startsWith('//')) {
+ return { href, kind: 'remote' };
+ }
+
+ const resolvedPath = assetPath.startsWith('/')
+ ? resolveAgainstDirectory(rootDirectory ?? workingDirectory, assetPath.slice(1), sourcePath)
+ : resolveAgainstDirectory(parentDirectory(sourcePath), assetPath, sourcePath);
+
+ if (!isPathInsideWorkspace(resolvedPath, workingDirectory)) {
+ return { absolutePath: resolvedPath, href, kind: 'escape' };
+ }
+
+ return { absolutePath: resolvedPath, href, kind: 'resolved' };
+};
+
+export const createWorkspaceHtmlArtifactIdentifier = (relativePath: string): string => {
+ const normalized = relativePath.replaceAll('\\', '/').replace(/^\/+/u, '');
+ const slug = normalized
+ .replaceAll(/[^a-z0-9]+/gi, '-')
+ .replaceAll(/^-+|-+$/g, '')
+ .toLowerCase()
+ .slice(0, 48);
+ const digest = sha256(normalized).slice(0, 10);
+
+ return `workspace-html-${slug || 'page'}-${digest}`;
+};
+
+export const workspaceHtmlArtifactIdentifierForFile = (
+ filePath: string,
+ workingDirectory: string,
+): string => {
+ const relativePath =
+ toWorkspaceRelativePath(
+ toWorkspaceAbsolutePath(filePath, workingDirectory),
+ workingDirectory,
+ ) ||
+ (stripTrailingSlash(toSlashPath(filePath)).split('/').at(-1) ?? filePath);
+ return createWorkspaceHtmlArtifactIdentifier(relativePath);
+};
+
+export { parentDirectory };
diff --git a/packages/html-artifact/vitest.config.mts b/packages/html-artifact/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/html-artifact/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 560a5f2fc93..270215c5b2d 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2773,6 +2773,8 @@ export default {
'workingPanel.localFile.publish.success': 'Published',
'workingPanel.localFile.publish.tooLarge': 'This page is too large to publish ({{size}} bytes).',
'workingPanel.localFile.publish.tooMany': 'This page references too many local files to publish.',
+ 'workingPanel.localFile.publish.unsupported':
+ 'These file types cannot be published and will be skipped: {{list}}',
'workingPanel.localFile.publish.unresolvedLocals':
'This page still points at local files that were not packed, so those assets would break after publish.',
'workingPanel.localFile.publish.version': 'Publish this version',
diff --git a/src/components/HtmlPreview/PreviewDrawer.tsx b/src/components/HtmlPreview/PreviewDrawer.tsx
index ac0fa0183c4..8744bb33637 100644
--- a/src/components/HtmlPreview/PreviewDrawer.tsx
+++ b/src/components/HtmlPreview/PreviewDrawer.tsx
@@ -1,4 +1,5 @@
import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';
+import { extractHtmlTitle } from '@lobechat/html-artifact';
import { exportFile } from '@lobechat/utils/client';
import { Block, Flexbox, Highlighter, HtmlPreview } from '@lobehub/ui';
import { Button, Drawer, Tabs } from '@lobehub/ui/base-ui';
@@ -9,8 +10,6 @@ import { useTranslation } from 'react-i18next';
import { isDesktop } from '@/const/version';
-import { extractHtmlTitle } from './htmlTagScanner';
-
const styles = createStaticStyles(({ css }) => ({
container: css`
height: 100%;
diff --git a/src/components/HtmlPreview/applyBaseUrl.ts b/src/components/HtmlPreview/applyBaseUrl.ts
index f24dbcf6930..626a88b7e56 100644
--- a/src/components/HtmlPreview/applyBaseUrl.ts
+++ b/src/components/HtmlPreview/applyBaseUrl.ts
@@ -1,4 +1,4 @@
-import { findAttribute, findOpeningTag } from './htmlTagScanner';
+import { findAttribute, findOpeningTag } from '@lobechat/html-artifact';
const escapeHtmlAttribute = (value: string): string =>
value.replaceAll('&', '&amp;').replaceAll('"', '&quot;');
diff --git a/src/features/Portal/LocalFile/Body.helpers.ts b/src/features/Portal/LocalFile/Body.helpers.ts
index ee949372ae8..2c67a2eef81 100644
--- a/src/features/Portal/LocalFile/Body.helpers.ts
+++ b/src/features/Portal/LocalFile/Body.helpers.ts
@@ -1,9 +1,49 @@
-export const getFileExtension = (filename: string): string => {
- const base = filename.split('/').at(-1) ?? filename;
- if (base.startsWith('.') && !base.slice(1).includes('.')) return '';
- const dotIdx = base.lastIndexOf('.');
- if (dotIdx < 0) return '';
- return base.slice(dotIdx + 1);
+export { getFileExtension } from '@lobechat/html-artifact';
+
+const EXT_TO_LANG: Record<string, string> = {
+ bash: 'bash',
+ c: 'c',
+ cpp: 'cpp',
+ cs: 'csharp',
+ css: 'css',
+ dockerfile: 'dockerfile',
+ fish: 'fish',
+ go: 'go',
+ graphql: 'graphql',
+ html: 'html',
+ java: 'java',
+ js: 'javascript',
+ json: 'json',
+ jsx: 'jsx',
+ kt: 'kotlin',
+ lua: 'lua',
+ md: 'markdown',
+ mdx: 'mdx',
+ php: 'php',
+ prisma: 'prisma',
+ proto: 'protobuf',
+ py: 'python',
+ rb: 'ruby',
+ rs: 'rust',
+ scala: 'scala',
+ scss: 'scss',
+ sh: 'bash',
+ sql: 'sql',
+ swift: 'swift',
+ tf: 'hcl',
+ toml: 'toml',
+ ts: 'typescript',
+ tsx: 'tsx',
+ txt: 'txt',
+ xml: 'xml',
+ yaml: 'yaml',
+ yml: 'yaml',
+ zsh: 'bash',
+};
+
+export const extensionToLanguage = (ext: string): string => {
+ if (!ext) return 'txt';
+ return EXT_TO_LANG[ext.toLowerCase()] ?? 'txt';
};
const URL_LIKE_PREFIX = /^(?:[a-z][a-z\d+.-]*:|\/\/|#|\/)/i;
diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
index a80f05e620d..da0d1ab3746 100644
--- a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
@@ -31,6 +31,7 @@ interface PublishHtmlArtifactConfirmContentProps {
missing: string[];
oversized: string[];
remotes: string[];
+ unsupported: string[];
uploadedPaths: string[];
}
@@ -40,10 +41,11 @@ const PublishHtmlArtifactConfirmContent = ({
missing,
oversized,
remotes,
+ unsupported,
uploadedPaths,
}: PublishHtmlArtifactConfirmContentProps) => {
const { t } = useTranslation('chat');
- const showDetails = [inlinedPaths, uploadedPaths, missing, oversized, remotes].some(
+ const showDetails = [inlinedPaths, uploadedPaths, missing, oversized, remotes, unsupported].some(
(list) => list.length > 0,
);
@@ -97,6 +99,13 @@ const PublishHtmlArtifactConfirmContent = ({
})}
</Text>
)}
+ {unsupported.length > 0 && (
+ <Text type={'secondary'}>
+ {t('workingPanel.localFile.publish.unsupported', {
+ list: unsupported.join(', '),
+ })}
+ </Text>
+ )}
{remotes.length > 0 && (
<>
<Text>{t('workingPanel.localFile.publish.remotes')}</Text>
@@ -183,6 +192,7 @@ export const openWorkspaceHtmlPublishConfirm = ({
missing={plan.gathered.missing}
oversized={plan.gathered.oversized}
remotes={plan.gathered.remotes}
+ unsupported={plan.gathered.unsupported}
uploadedPaths={plan.packed.sidecars.map((file) => file.path)}
/>
),
diff --git a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts
index f93fbbab2f1..ac2adfe2dee 100644
--- a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts
+++ b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.ts
@@ -1,19 +1,15 @@
-import { toast } from '@lobehub/ui/base-ui';
-import { t } from 'i18next';
-
import {
type GatheredWorkspaceHtmlArtifact,
gatherWorkspaceHtmlArtifact,
-} from './gatherWorkspaceHtmlArtifact';
-import {
type PackedWorkspaceHtmlSite,
packWorkspaceHtmlDocument,
-} from './packWorkspaceHtmlDocument';
+ type WorkspaceHtmlArtifactPublisher,
+ type WorkspaceHtmlArtifactPublishResult,
+} from '@lobechat/html-artifact';
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
import { readWorkspaceAsset } from './readWorkspaceAsset';
-import type {
- WorkspaceHtmlArtifactPublisher,
- WorkspaceHtmlArtifactPublishResult,
-} from './workspaceHtmlArtifact';
export interface ReadyWorkspaceHtmlPublishPlan {
gathered: GatheredWorkspaceHtmlArtifact;
diff --git a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts
index c126ab7afa5..feca49b328c 100644
--- a/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts
+++ b/src/features/Portal/LocalFile/publishWorkspaceHtmlArtifact.ts
@@ -1,125 +1,6 @@
-import { ARTIFACT_TAG } from '@lobechat/const';
-import { escapeXmlAttr } from '@lobechat/prompts';
-
-import { hostedPath, packWorkspaceHtmlDocument } from './packWorkspaceHtmlDocument';
-import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './readWorkspaceAsset';
-import type {
- WorkspaceHtmlArtifactFile,
- WorkspaceHtmlArtifactPublishInput,
- WorkspaceHtmlArtifactPublishResult,
-} from './workspaceHtmlArtifact';
-
-export const wrapWorkspaceHtmlArtifact = ({
- html,
- identifier,
- title,
-}: {
- html: string;
- identifier: string;
- title: string;
-}): string =>
- `<${ARTIFACT_TAG} identifier="${escapeXmlAttr(identifier)}" type="text/html" title="${escapeXmlAttr(title)}">\n${html}\n</${ARTIFACT_TAG}>`;
-
-export interface PublishWorkspaceHtmlSiteParams {
- artifactIdentifier: string;
- files: WorkspaceHtmlArtifactFile[];
- html: string;
- onPhase?: WorkspaceHtmlArtifactPublishInput['onUploadPhase'];
- onProgress?: WorkspaceHtmlArtifactPublishInput['onUploadProgress'];
- requestedSlug?: string;
- signal?: AbortSignal;
- title?: string;
- topicId: string;
-}
-
-export const publishWorkspaceHtmlArtifact = async (
- input: WorkspaceHtmlArtifactPublishInput,
- deps: {
- createMessage: (params: {
- agentId: string;
- content: string;
- role: 'assistant';
- topicId: string;
- }) => Promise<{ id: string }>;
- publishArtifact: (params: {
- artifactIdentifier: string;
- messageId: string;
- requestedSlug?: string;
- topicId: string;
- }) => Promise<{ id?: string; latestRevisionNumber?: number; publicUrl?: string }>;
- publishSite?: (
- params: PublishWorkspaceHtmlSiteParams,
- ) => Promise<{ id?: string; latestRevisionNumber?: number; publicUrl?: string }>;
- },
-): Promise<WorkspaceHtmlArtifactPublishResult> => {
- const packed =
- input.packed ??
- (() => {
- const fresh = packWorkspaceHtmlDocument({
- entryPath: input.entryPath,
- files: input.files,
- });
- if (fresh.unresolvedHrefs.length > 0) {
- throw new Error('unresolved-local-assets');
- }
- return fresh;
- })();
-
- if (
- packed.sidecars.length > 0 ||
- new TextEncoder().encode(packed.html).byteLength > WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES
- ) {
- if (!deps.publishSite) {
- throw new Error('unavailable');
- }
-
- const deployment = await deps.publishSite({
- artifactIdentifier: input.identifier,
- files: packed.sidecars.map((file) => ({
- ...file,
- path: hostedPath(file.path),
- })),
- html: packed.html,
- onPhase: input.onUploadPhase,
- onProgress: input.onUploadProgress,
- requestedSlug: input.title,
- signal: input.signal,
- title: input.title,
- topicId: input.topicId,
- });
-
- return {
- id: deployment.id,
- publicUrl: deployment.publicUrl,
- revision: deployment.latestRevisionNumber,
- };
- }
-
- if (!input.agentId) {
- throw new Error('unavailable');
- }
-
- const message = await deps.createMessage({
- agentId: input.agentId,
- content: wrapWorkspaceHtmlArtifact({
- html: packed.html,
- identifier: input.identifier,
- title: input.title,
- }),
- role: 'assistant',
- topicId: input.topicId,
- });
-
- const deployment = await deps.publishArtifact({
- artifactIdentifier: input.identifier,
- messageId: message.id,
- requestedSlug: input.title,
- topicId: input.topicId,
- });
-
- return {
- id: deployment.id,
- publicUrl: deployment.publicUrl,
- revision: deployment.latestRevisionNumber,
- };
-};
+/**
+ * Moved to `@lobechat/html-artifact`. Kept as a re-export because the closed
+ * business overlay still imports this path; delete once that side migrates.
+ */
+export type { PublishWorkspaceHtmlSiteParams } from '@lobechat/html-artifact';
+export { publishWorkspaceHtmlArtifact, wrapWorkspaceHtmlArtifact } from '@lobechat/html-artifact';
diff --git a/src/features/Portal/LocalFile/readWorkspaceAsset.ts b/src/features/Portal/LocalFile/readWorkspaceAsset.ts
index e85d54feff3..c936e613ff2 100644
--- a/src/features/Portal/LocalFile/readWorkspaceAsset.ts
+++ b/src/features/Portal/LocalFile/readWorkspaceAsset.ts
@@ -1,53 +1,26 @@
+import {
+ isTextContentType,
+ type ReadWorkspaceAssetResult,
+ resolveWorkspaceAssetContentType,
+ WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES,
+} from '@lobechat/html-artifact';
import { base64ToBytes, getMimeType } from '@lobechat/utils';
import { cloudSandboxService } from '@/services/cloudSandbox';
import { type LocalFilePreview, projectFileService } from '@/services/projectFile';
-export const WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES = 50 * 1024 * 1024;
-export const WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
-export const WORKSPACE_HTML_ARTIFACT_MAX_FILES = 64;
-export const WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES = 32 * 1024;
-
-export type ReadWorkspaceAssetFailure = 'missing' | 'oversized' | 'unreadable';
-
-export interface ReadWorkspaceAssetSuccess {
- bytes: Uint8Array;
- contentType: string;
- ok: true;
- text?: string;
-}
-
-export interface ReadWorkspaceAssetError {
- ok: false;
- reason: ReadWorkspaceAssetFailure;
- sizeBytes?: number;
-}
-
-export type ReadWorkspaceAssetResult = ReadWorkspaceAssetError | ReadWorkspaceAssetSuccess;
-
-const TEXT_CONTENT_TYPES = new Set([
- 'application/javascript',
- 'application/json',
- 'application/xml',
- 'image/svg+xml',
- 'text/css',
- 'text/html',
- 'text/javascript',
- 'text/plain',
-]);
-
-const isTextContentType = (contentType: string): boolean => {
- const bare = contentType.split(';')[0].trim().toLowerCase();
- return bare.startsWith('text/') || TEXT_CONTENT_TYPES.has(bare);
-};
-
-export const resolveWorkspaceAssetContentType = (path: string, reported?: string): string => {
- const guessed = getMimeType(path);
- if (guessed !== 'application/octet-stream') return guessed;
-
- const reportedType = reported?.split(';')[0]?.trim();
- return reportedType || guessed;
-};
+export {
+ isTextContentType,
+ type ReadWorkspaceAssetError,
+ type ReadWorkspaceAssetFailure,
+ type ReadWorkspaceAssetResult,
+ type ReadWorkspaceAssetSuccess,
+ resolveWorkspaceAssetContentType,
+ WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES,
+ WORKSPACE_HTML_ARTIFACT_MAX_FILE_BYTES,
+ WORKSPACE_HTML_ARTIFACT_MAX_FILES,
+ WORKSPACE_HTML_ARTIFACT_MAX_TOTAL_BYTES,
+} from '@lobechat/html-artifact';
const quoteShellArg = (value: string): string => `'${value.replaceAll("'", `'\\''`)}'`;
diff --git a/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts b/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts
index 3ee695a4a1e..2df941a0ce1 100644
--- a/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts
+++ b/src/features/Portal/LocalFile/workspaceHtmlArtifact.ts
@@ -1,49 +1,11 @@
-export interface WorkspaceHtmlArtifactFile {
- content: string;
- contentType: string;
- encoding: 'base64' | 'utf8';
- path: string;
-}
-
-export interface WorkspaceHtmlArtifactPublishInput {
- agentId?: string;
- entryPath: string;
- files: WorkspaceHtmlArtifactFile[];
- identifier: string;
- onUploadPhase?: (phase: 'finalizing' | 'preparing' | 'uploading') => void;
- onUploadProgress?: (progress: {
- completedFiles: number;
- loadedBytes: number;
- totalBytes: number;
- totalFiles: number;
- }) => void;
- packed?: { html: string; sidecars: WorkspaceHtmlArtifactFile[] };
- signal?: AbortSignal;
- title: string;
- topicId: string;
-}
-
-export interface WorkspaceHtmlArtifactExisting {
- id?: string;
- identifier: string;
- publicUrl?: string;
- revision?: number;
- status?: string;
-}
-
-export interface WorkspaceHtmlArtifactPublishResult {
- id?: string;
- publicUrl?: string;
- revision?: number;
-}
-
-export interface WorkspaceHtmlArtifactPublisher {
- available: boolean;
- getExisting: (input: {
- identifier: string;
- topicId: string;
- }) => Promise<WorkspaceHtmlArtifactExisting | null>;
- publish: (
- input: WorkspaceHtmlArtifactPublishInput,
- ) => Promise<WorkspaceHtmlArtifactPublishResult>;
-}
+/**
+ * Moved to `@lobechat/html-artifact`. Kept as a re-export because the closed
+ * business overlay still imports this path; delete once that side migrates.
+ */
+export type {
+ WorkspaceHtmlArtifactExisting,
+ WorkspaceHtmlArtifactFile,
+ WorkspaceHtmlArtifactPublisher,
+ WorkspaceHtmlArtifactPublishInput,
+ WorkspaceHtmlArtifactPublishResult,
+} from '@lobechat/html-artifact';
diff --git a/src/features/Portal/LocalFile/workspaceHtmlPath.ts b/src/features/Portal/LocalFile/workspaceHtmlPath.ts
index 1196a18c584..9922accf40c 100644
--- a/src/features/Portal/LocalFile/workspaceHtmlPath.ts
+++ b/src/features/Portal/LocalFile/workspaceHtmlPath.ts
@@ -1,213 +1,14 @@
-import { sha256 } from 'js-sha256';
-
-const toSlashPath = (filePath: string): string => filePath.replaceAll('\\', '/');
-
-const fromSlashPath = (filePath: string, sourcePath: string): string => {
- const usesWindowsSeparator = sourcePath.includes('\\') && !sourcePath.includes('/');
- return usesWindowsSeparator ? filePath.replaceAll('/', '\\') : filePath;
-};
-
-const stripTrailingSlash = (value: string) => (value.endsWith('/') ? value.slice(0, -1) : value);
-
-const DARWIN_PRIVATE_ROOTS = ['/tmp', '/var', '/etc'] as const;
-
-const canonicalizeWorkspacePath = (filePath: string): string => {
- const slashPath = stripTrailingSlash(toSlashPath(filePath));
-
- for (const root of DARWIN_PRIVATE_ROOTS) {
- const privateRoot = `/private${root}`;
- if (slashPath === privateRoot || slashPath.startsWith(`${privateRoot}/`)) {
- return slashPath.slice('/private'.length);
- }
- }
-
- return slashPath;
-};
-
-const decodePathSegment = (segment: string): string => {
- try {
- return decodeURIComponent(segment);
- } catch {
- return segment;
- }
-};
-
-const splitResourceHref = (href: string): string => {
- const queryIndex = href.indexOf('?');
- const hashIndex = href.indexOf('#');
- const suffixIndex = [queryIndex, hashIndex]
- .filter((index) => index >= 0)
- .sort((a, b) => a - b)[0];
- return (suffixIndex === undefined ? href : href.slice(0, suffixIndex)).trim();
-};
-
-const normalizeSlashPath = (
- filePath: string,
- { preserveLeadingDoubleSlash = false }: { preserveLeadingDoubleSlash?: boolean } = {},
-): string => {
- const leadingEmptySegmentLimit = preserveLeadingDoubleSlash && filePath.startsWith('//') ? 2 : 1;
- const normalizedSegments: string[] = [];
-
- for (const segment of filePath.split('/')) {
- if (!segment || segment === '.') {
- if (
- segment === '' &&
- normalizedSegments.length < leadingEmptySegmentLimit &&
- normalizedSegments.every((item) => item === '')
- ) {
- normalizedSegments.push('');
- }
- continue;
- }
-
- if (segment === '..') {
- if (normalizedSegments.length > 1) normalizedSegments.pop();
- continue;
- }
-
- normalizedSegments.push(segment);
- }
-
- return normalizedSegments.join('/') || '/';
-};
-
-const parentDirectory = (filePath: string): string => {
- const slashPath = toSlashPath(filePath);
- const isUncPath = slashPath.startsWith('//');
- const lastSeparatorIndex = slashPath.lastIndexOf('/');
- if (lastSeparatorIndex < 0) return '';
- if (slashPath.startsWith('/') && lastSeparatorIndex === 0) return '/';
- const directory = slashPath.slice(0, lastSeparatorIndex);
- return fromSlashPath(isUncPath && directory === '' ? '//' : directory, filePath);
-};
-
-export const isPathInsideWorkspace = (targetPath: string, workingDirectory: string): boolean => {
- const target = canonicalizeWorkspacePath(targetPath);
- const root = canonicalizeWorkspacePath(workingDirectory);
- return target === root || target.startsWith(`${root}/`);
-};
-
-export const toWorkspaceAbsolutePath = (filePath: string, workingDirectory: string): string => {
- const slashPath = toSlashPath(filePath);
- if (isPathInsideWorkspace(filePath, workingDirectory)) {
- return fromSlashPath(slashPath, workingDirectory);
- }
-
- const isAbsolute = slashPath.startsWith('/') || /^[a-zA-Z]:/u.test(filePath);
- if (isAbsolute) return filePath;
-
- const root = stripTrailingSlash(toSlashPath(workingDirectory));
- return fromSlashPath(normalizeSlashPath(`${root}/${slashPath}`), workingDirectory);
-};
-
-export const toWorkspaceRelativePath = (absolutePath: string, workingDirectory: string): string => {
- const target = canonicalizeWorkspacePath(absolutePath);
- const root = canonicalizeWorkspacePath(workingDirectory);
- if (target === root) return '';
- if (target.startsWith(`${root}/`)) return target.slice(root.length + 1);
- return stripTrailingSlash(toSlashPath(absolutePath)).split('/').at(-1) ?? absolutePath;
-};
-
-export const lowestCommonAncestorDirectory = (
- absolutePaths: string[],
- workingDirectory: string,
-): string => {
- if (absolutePaths.length === 0) return workingDirectory;
-
- const relativeDirs = absolutePaths.map((absolutePath) => {
- const relativePath = toWorkspaceRelativePath(absolutePath, workingDirectory);
- const segments = relativePath.split('/').filter(Boolean);
- return segments.slice(0, -1);
- });
-
- const [first, ...rest] = relativeDirs;
- const common: string[] = [];
-
- for (const [index, segment] of first.entries()) {
- if (rest.every((dirs) => dirs[index] === segment)) {
- common.push(segment);
- continue;
- }
- break;
- }
-
- if (common.length === 0) return workingDirectory;
-
- const slashRoot = `${stripTrailingSlash(toSlashPath(workingDirectory))}/${common.join('/')}`;
- return fromSlashPath(slashRoot, workingDirectory);
-};
-
-const joinPath = (basePath: string, segments: string[], sourcePath: string): string => {
- const slashBase = toSlashPath(basePath);
- const isUncPath = slashBase.startsWith('//');
- const resolved = normalizeSlashPath(
- slashBase ? [slashBase, ...segments].join('/') : segments.join('/'),
- {
- preserveLeadingDoubleSlash: isUncPath,
- },
- );
- return fromSlashPath(resolved, sourcePath);
-};
-
-const resolveAgainstDirectory = (directory: string, href: string, sourcePath: string): string => {
- const segments = href.split(/[\\/]+/).map(decodePathSegment);
- return joinPath(directory, segments, sourcePath);
-};
-
-export const resolveLocalResourceHref = ({
- href,
- rootDirectory,
- sourcePath,
- workingDirectory,
-}: {
- href: string;
- rootDirectory?: string;
- sourcePath: string;
- workingDirectory: string;
-}): { absolutePath?: string; href: string; kind: 'empty' | 'escape' | 'remote' | 'resolved' } => {
- const assetPath = splitResourceHref(href);
- if (!assetPath || assetPath === '#' || assetPath.startsWith('#')) {
- return { href, kind: 'empty' };
- }
-
- if (/^[a-z][a-z\d+.-]*:/i.test(assetPath) || assetPath.startsWith('//')) {
- return { href, kind: 'remote' };
- }
-
- const resolvedPath = assetPath.startsWith('/')
- ? resolveAgainstDirectory(rootDirectory ?? workingDirectory, assetPath.slice(1), sourcePath)
- : resolveAgainstDirectory(parentDirectory(sourcePath), assetPath, sourcePath);
-
- if (!isPathInsideWorkspace(resolvedPath, workingDirectory)) {
- return { absolutePath: resolvedPath, href, kind: 'escape' };
- }
-
- return { absolutePath: resolvedPath, href, kind: 'resolved' };
-};
-
-export const createWorkspaceHtmlArtifactIdentifier = (relativePath: string): string => {
- const normalized = relativePath.replaceAll('\\', '/').replace(/^\/+/u, '');
- const slug = normalized
- .replaceAll(/[^a-z0-9]+/gi, '-')
- .replaceAll(/^-+|-+$/g, '')
- .toLowerCase()
- .slice(0, 48);
- const digest = sha256(normalized).slice(0, 10);
-
- return `workspace-html-${slug || 'page'}-${digest}`;
-};
-
-export const workspaceHtmlArtifactIdentifierForFile = (
- filePath: string,
- workingDirectory: string,
-): string => {
- const relativePath =
- toWorkspaceRelativePath(
- toWorkspaceAbsolutePath(filePath, workingDirectory),
- workingDirectory,
- ) ||
- (stripTrailingSlash(toSlashPath(filePath)).split('/').at(-1) ?? filePath);
- return createWorkspaceHtmlArtifactIdentifier(relativePath);
-};
-
-export { parentDirectory };
+/**
+ * Moved to `@lobechat/html-artifact`. Kept as a re-export because the closed
+ * business overlay still imports this path; delete once that side migrates.
+ */
+export {
+ createWorkspaceHtmlArtifactIdentifier,
+ isPathInsideWorkspace,
+ lowestCommonAncestorDirectory,
+ parentDirectory,
+ resolveLocalResourceHref,
+ toWorkspaceAbsolutePath,
+ toWorkspaceRelativePath,
+ workspaceHtmlArtifactIdentifierForFile,
+} from '@lobechat/html-artifact';