@absolutejs/artifacts

中文文档
0.5.0发布于 2026/11/06BUSL-1.1TypeScriptES Module近 30 天下载 1784

Typed, versioned artifacts for AI products — schemas, lifecycle, storage, rendering, publishing, revisions, and agent tools without prescribing a database or host.

原始使用文档
文档目录12 节
  1. What it owns
  2. Define kinds once
  3. Production persistence
  4. File-backed artifact kinds
  5. Generation
  6. RAG ingestion
  7. Events and retention
  8. Compose publishing and rendering
  9. AI tools
  10. License
  11. Browser document preview
  12. Formatted Word exports

@absolutejs/artifacts

The typed lifecycle for things an AI makes.

An AI-generated page, report, plan, email, deck, or image should not disappear into a chat transcript or become an unvalidated blob. It should have a kind, structured content, ownership, provenance, revisions, capabilities, renderers, and an explicit publication lifecycle.

@absolutejs/artifacts provides those contracts without owning your database, routes, authorization, UI, or hosting.

What it owns

  • Structured artifact-kind schemas and runtime validation
  • Draft, published, and archived lifecycle states
  • Immutable revision history, restoration, and optimistic updates
  • Structured content plus opaque references to generated or source files
  • Artifact, asset, renderer, and publisher storage interfaces
  • In-memory artifact and asset stores for development and tests
  • Owner-bound lifecycle tools structurally compatible with AI tool maps
  • Provenance fields for model, tool, trace, and source entities
  • Standard file-backed kinds for documents, presentations, spreadsheets, datasets, code, images, audio, video, email, archives, and generic files
  • An optional bridge to @absolutejs/rag ingestion
  • Provider-neutral generation registries with atomic multi-file bundles
  • Staged, validate-before-commit multi-artifact batches with completion receipts
  • Revision-pinned or explicitly live publications
  • Durable lifecycle events designed for transactional outboxes
  • Per-revision RAG indexing state and an indexing coordinator
  • Artifact/source lineage and history-aware asset garbage collection

Your application retains authorization, durable persistence, public tokens, URLs, notifications, analytics, submissions, and product-specific rendering.

Define kinds once

import { Type } from "@sinclair/typebox";
import {
  createArtifactService,
  createMemoryArtifactAssetStore,
  createMemoryArtifactStore,
  defineArtifactRegistry,
} from "@absolutejs/artifacts";

const registry = defineArtifactRegistry({
  page: {
    capabilities: ["archive", "edit", "preview", "publish"],
    content: Type.Object({
      blocks: Type.Array(
        Type.Union([
          Type.Object({ heading: Type.String(), type: Type.Literal("hero") }),
          Type.Object({ body: Type.String(), type: Type.Literal("text") }),
        ]),
      ),
      theme: Type.Union([Type.Literal("dark"), Type.Literal("light")]),
    }),
    label: "Page",
    schemaVersion: 1,
  },
});

const artifacts = createArtifactService({
  assetStore: createMemoryArtifactAssetStore(),
  registry,
  store: createMemoryArtifactStore(),
});

const page = await artifacts.create("owner-123", {
  content: {
    blocks: [{ heading: "A real page", type: "hero" }],
    theme: "light",
  },
  createdBy: "agent",
  kind: "page",
  provenance: { model: "your-model", tool: "create_page" },
  title: "Launch page",
});

Every successful create or lifecycle mutation appends an immutable snapshot. Restoring history creates a new private draft instead of rewriting or republishing an old revision:

const history = await artifacts.listRevisions("owner-123", page.id);
const restored = await artifacts.restore("owner-123", page.id, 1);

Production persistence

Use the package-owned Drizzle schema on PostgreSQL, including Neon. The store atomically writes the current artifact, immutable revision, and lifecycle outbox events. It also persists per-revision indexing state and fences every artifact read and mutation by owner.

import {
  artifactDrizzleSchema,
  createDrizzleArtifactStore,
} from "@absolutejs/artifacts/drizzle";

const store = createDrizzleArtifactStore({ db });

Export artifactDrizzleSchema from your application's Drizzle schema so its normal migration workflow owns the four tables. Insert and select TypeBoxes generated directly from those tables are exported from the same entry point; hosts should reuse them instead of redefining database row schemas.

When a host owner is permanently deleted, call artifacts.purgeOwner(ownerId). The production store removes its current records, revisions, indexing state, and outbox events in one transaction; orphaned asset bytes remain subject to the package's history-aware garbage collector.

File-backed artifact kinds

Use the bundled definitions directly or compose them with application-specific kinds:

import {
  defineArtifactRegistry,
  standardArtifactDefinitions,
} from "@absolutejs/artifacts";

const registry = defineArtifactRegistry({
  ...standardArtifactDefinitions,
  page: myPageDefinition,
});

File bytes stay in host storage. Artifact records retain opaque references with name, media type, size, checksum, role, and storage URI. The URI is not treated as a public URL and the package reads it only through the configured asset store. Detaching a file does not delete its bytes because older immutable revisions may still reference it.

const report = await artifacts.create("owner-123", {
  content: { summary: "Quarterly results" },
  createdBy: "agent",
  kind: "document",
  title: "Q3 report",
});

await artifacts.attach("owner-123", report.id, {
  data: pdfBytes,
  mediaType: "application/pdf",
  name: "q3-report.pdf",
  role: "primary",
});

Multiple generated files should use one staged transaction and therefore one artifact revision:

const report = await artifacts.createBundle("owner-123", {
  assets: [pdfOutput, docxOutput, thumbnailOutput],
  content: { summary: "Quarterly results" },
  createdBy: "agent",
  kind: "document",
  provenance: {
    lineage: [{ relation: "generated_from", sourceId: "rag-document-123" }],
    tool: "quarterly_report_generator",
  },
  title: "Q3 report",
});

When one job must produce several artifacts together, stage the complete batch, run domain validators before persistence, and commit it through a store that implements createBatch (the package Drizzle and memory stores do):

const staged = await artifacts.stageBatch(
  "owner-123",
  {
    evidence: [{ sourceId: "research-run-123", sourceUrl: sourceUrl }],
    items: [
      { artifact: worksheetInput, key: "worksheet" },
      { artifact: reportInput, key: "report" },
    ],
    provenance: { tool: "prospecting_mission", traceId: mission.id },
  },
  {
    validators: [
      ({ items }) =>
        validateDomainEvidence(items).map((message) => ({
          code: "evidence_invalid",
          message,
        })),
    ],
  },
);

const receipt = await staged.commit();
if (receipt.status !== "committed") throw new Error(receipt.error);

Every artifact carries its batch id, item key, evidence, and provenance. commit() returns the durable reconciliation receipt: artifact ids, revisions, atomicity, validation outcome, and any archived compensation. The default mode requires an atomic ArtifactStore.createBatch. Hosts that cannot provide a transaction may explicitly select archive_on_failure; completed earlier writes are then archived and reported as rolled_back or partial_failure. Calling rollback() before commit releases all staged asset transactions.

Generation

Generators are provider-neutral. They return validated structured content and zero or more file writes; the registry commits those outputs through the same artifact bundle lifecycle:

const generators = createArtifactGeneratorRegistry([
  {
    kind: "presentation",
    name: "company-deck",
    generate: async ({ prompt }) => buildPresentation(prompt),
  },
]);

const deck = await generators.generate(artifacts, {
  createdBy: "agent",
  kind: "presentation",
  ownerId: member.id,
  prompt: "Build the partner launch deck",
});

Generators may expose a validate function. The bundled validateGeneratedArtifactFormats validator checks CSV row structure, RFC 822 headers, ZIP readability, and PPTX package/XML integrity before persistence. Generate several independent artifacts with one atomic receipt through the same registry:

const receipt = await generators.generateBatch(artifacts, {
  ownerId: member.id,
  items: [
    { createdBy: "agent", key: "deck", kind: "presentation", title: "Deck" },
    { createdBy: "agent", key: "email", kind: "email", title: "Email" },
  ],
  provenance: { tool: "campaign_generator" },
});

Generation validators run after every output is staged and before anything is committed. Validation failures return a rolled-back completion receipt keyed to the invalid output.

RAG ingestion

The optional @absolutejs/artifacts/rag entry point resolves one current or historical artifact record into the upload contract already accepted by @absolutejs/rag. Structured content is included as JSON and every attached file is included without exposing its storage URI:

import { artifactToRAGUploads } from "@absolutejs/artifacts/rag";
import { buildRAGUpsertInputFromUploads } from "@absolutejs/rag";

const revision = await artifacts.getRevision("owner-123", report.id, 2);
const uploads = await artifactToRAGUploads(revision, assetStore);
const upsert = await buildRAGUpsertInputFromUploads({ uploads });

createArtifactRAGIndexCoordinator wraps that conversion with durable pending, indexed, and failed state. It removes document IDs from the previous indexed revision after the replacement succeeds. Set failureMode to "isolate_uploads" to index structured content and assets independently. A bad asset then produces a typed partial receipt while preserving successful document ids; obsolete ids are removed only after a fully successful revision.

Events and retention

Every lifecycle mutation supplies its event to the artifact store in the same call that writes the current record and immutable revision. Durable adapters should commit those rows in one database transaction, then workers can consume unprocessed events for RAG indexing, previews, notifications, scanning, or conversion.

Asset collection compares storage candidates with references across every retained revision. collectAssetGarbage({ dryRun: true }) previews deletion; only unreferenced objects older than the configured minimum age are eligible.

Compose publishing and rendering

Publishing is an adapter because public access is a host policy:

const artifacts = createArtifactService({
  publisher: {
    publish: async (artifact, { idempotencyKey }) =>
      mintPublicTokenAndUrl(artifact, idempotencyKey),
    unpublish: async (artifact, { idempotencyKey }) =>
      revokePublicAccess(artifact, idempotencyKey),
  },
  registry,
  store: postgresArtifactStore,
});

Publishing defaults to pinned: the public record names the exact immutable revision. mode: "live" is an explicit alternative whose revision advances with later edits.

Renderers are independently registered by artifact kind and output format:

const renderers = createArtifactRendererRegistry([
  {
    format: "html",
    kind: "page",
    render: async (artifact) => ({
      body: renderSafePage(artifact.content),
      mediaType: "text/html; charset=utf-8",
    }),
  },
]);

The package never treats generated HTML or JavaScript as trusted executable content. Applications should define structured content schemas and render them through controlled adapters.

AI tools

createArtifactTools binds create, list, get, update, publish, and unpublish operations to one owner. The returned definitions use TypeBox inputs and the same { description, input, handler } shape used by @absolutejs/ai.

const tools = createArtifactTools({
  createdBy: "agent",
  ownerId: member.id,
  service: artifacts,
});

Only expose the publication tool where the user explicitly controls public access.

License

Business Source License 1.1 — free for your own products, applications, and internal use; you may not offer it as a competing hosted AI artifact-generation, editing, rendering, publishing, or artifact-management service. Converts to Apache 2.0 on July 14, 2030. See LICENSE.

Browser document preview

Install the optional docx-preview peer and import renderDocxPreview from @absolutejs/artifacts/browser. Pass the original DOCX ArrayBuffer and display the returned HTML as srcDoc in an iframe with sandbox="". Keep that sandbox: the renderer disables active content, external resources, HTML chunks and links. Fetch bytes through your application's authenticated owner-scoped file endpoint. The browser preview approximates Word layout; always retain the original file.

Pass { allowLinks: true } to preserve validated HTTPS and plain email links. Use sandbox="allow-popups allow-popups-to-escape-sandbox" for this mode: links open outside the document sandbox in a new tab with no opener or referrer. Document scripts and parent-page navigation remain disabled. Links remain disabled by default. HTTP, executable URLs, credentials, and email parameters are not accepted.

Formatted Word exports

renderFormattedDocx({ blocks, filename, pageSize: 'letter' }) returns an ArtifactRenderResult containing editable DOCX bytes. Blocks are paragraphs, headings, or bullets; runs support bold, italic, and HTTPS/mailto hyperlinks. No resources are fetched. The default body font is 11.5 points. Documents are limited to 2,000 blocks and 1 MB of structured input.

For simple generated drafts, documentBlocksFromText(text) recognizes blank-line paragraphs, #/## headings, -/*/• bullets, **bold**, Markdown links and bare HTTPS URLs. This is a limited text format, not a complete Markdown renderer; HTML remains literal text. Layout can vary between Word-compatible applications.

版本与发布记录

@absolutejs/artifacts 共发布 20 个版本,首次发布于 2026/07/15;过去 12 个月发布了 20 个版本。

版本发布日期距今
0.5.0latest2026/11/062 天前
0.4.12026/11/062 天前
0.4.02026/11/053 天前
0.3.22026/10/2910 天前
0.3.12026/09/251 个月前
0.3.02026/09/012 个月前

其他发布通道:beta → 0.1.5-beta.0。

关于 @absolutejs/artifacts 的常见问题

@absolutejs/artifacts 是什么?

Typed, versioned artifacts for AI products — schemas, lifecycle, storage, rendering, publishing, revisions, and agent tools without prescribing a database or host.

如何安装 @absolutejs/artifacts?

在项目目录运行 npm install @absolutejs/artifacts,或使用 pnpm add / yarn add / bun add。

@absolutejs/artifacts 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@absolutejs/artifacts 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@absolutejs/artifacts 可以商用吗?

@absolutejs/artifacts 使用 BUSL-1.1 许可。声明的许可为 BUSL-1.1,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@absolutejs/artifacts 的下载量有多少?

根据 npm 官方下载统计,@absolutejs/artifacts 在 2026/10/05 – 2026/11/03 这 30 天内被下载 1,784 次,日均约 59 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@absolutejs/artifacts 还在维护吗?

最新版本 0.5.0 发布于 2026/11/06(2 天前);至今共发布 20 个版本,其中过去 12 个月发布了 20 个;首次发布于 2026/07/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。