Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a64708f3de | ||
|
|
98d4fd4960 | ||
|
|
3f634eb655 | ||
|
|
5173b6c8d6 | ||
|
|
2fa0baa577 | ||
|
|
668bf05b48 | ||
|
|
b8c0444217 | ||
|
|
13f28ef811 | ||
|
|
e49d90f713 |
@@ -31,6 +31,16 @@ module.exports = {
|
|||||||
path: "^(src/(application|adapters|bootstrap)|src/presentation/adapters|@tanstack)",
|
path: "^(src/(application|adapters|bootstrap)|src/presentation/adapters|@tanstack)",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "icon-vendor-is-facade-only",
|
||||||
|
severity: "error",
|
||||||
|
from: {
|
||||||
|
path: "^src",
|
||||||
|
pathNot:
|
||||||
|
"^src/presentation/design-system/icons/vendors/lucide\\.tsx$",
|
||||||
|
},
|
||||||
|
to: { path: "^lucide-react$" },
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: "adapters-do-not-know-presentation",
|
name: "adapters-do-not-know-presentation",
|
||||||
severity: "error",
|
severity: "error",
|
||||||
|
|||||||
@@ -10,4 +10,7 @@ artifacts/**/*.xml
|
|||||||
artifacts/**/*.txt
|
artifacts/**/*.txt
|
||||||
artifacts/**/*.sarif
|
artifacts/**/*.sarif
|
||||||
artifacts/tests/e2e/
|
artifacts/tests/e2e/
|
||||||
|
artifacts/storybook/
|
||||||
|
artifacts/tests/storybook/
|
||||||
|
artifacts/tests/visual/
|
||||||
!artifacts/**/.gitkeep
|
!artifacts/**/.gitkeep
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import type { StorybookConfig } from "@storybook/react-vite";
|
||||||
|
|
||||||
|
const config: StorybookConfig = {
|
||||||
|
stories: ["../src/**/*.stories.@(js|jsx|ts|tsx)"],
|
||||||
|
addons: ["@storybook/addon-a11y"],
|
||||||
|
framework: {
|
||||||
|
name: "@storybook/react-vite",
|
||||||
|
options: {},
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
disableTelemetry: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import type { Preview } from "@storybook/react-vite";
|
||||||
|
import { QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { MemoryRouter } from "react-router-dom";
|
||||||
|
|
||||||
|
import { createAnonymousSessionAdapter } from "../src/adapters/auth/external-session-adapter.js";
|
||||||
|
import { createQueryClient } from "../src/adapters/query-cache/tanstack-query-cache.js";
|
||||||
|
import { createApplication } from "../src/application/create-application.js";
|
||||||
|
import { LocaleProvider } from "../src/presentation/i18n/index.js";
|
||||||
|
import { ApplicationProvider } from "../src/presentation/providers/application-provider.js";
|
||||||
|
import { SessionProvider } from "../src/presentation/providers/session-provider.jsx";
|
||||||
|
import { ThemeProvider } from "../src/presentation/providers/theme-provider.jsx";
|
||||||
|
import "../src/presentation/styles/theme.css";
|
||||||
|
|
||||||
|
const preferences = new Map<string, unknown>();
|
||||||
|
const application = createApplication({
|
||||||
|
session: createAnonymousSessionAdapter(),
|
||||||
|
preferences: {
|
||||||
|
read: (name) => ({ ok: true, value: preferences.get(name) }),
|
||||||
|
write: (name, value) => {
|
||||||
|
preferences.set(name, structuredClone(value));
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
remove: (name) => {
|
||||||
|
preferences.delete(name);
|
||||||
|
return { ok: true };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
diagnostics: { record() {} },
|
||||||
|
telemetry: { emit() {} },
|
||||||
|
releaseInfo: {
|
||||||
|
getCurrent: async () => ({
|
||||||
|
buildId: "storybook-build",
|
||||||
|
releaseId: "storybook-release",
|
||||||
|
configSchemaVersion: "1",
|
||||||
|
apiContractVersion: "1",
|
||||||
|
assetManifestHash: "storybook-assets",
|
||||||
|
routeChunks: {},
|
||||||
|
}),
|
||||||
|
refresh: async () => ({
|
||||||
|
buildId: "storybook-build",
|
||||||
|
releaseId: "storybook-release",
|
||||||
|
configSchemaVersion: "1",
|
||||||
|
apiContractVersion: "1",
|
||||||
|
assetManifestHash: "storybook-assets",
|
||||||
|
routeChunks: {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
navigation: { reload() {} },
|
||||||
|
});
|
||||||
|
const queryClient = createQueryClient();
|
||||||
|
|
||||||
|
const preview: Preview = {
|
||||||
|
decorators: [
|
||||||
|
(Story) => (
|
||||||
|
<ApplicationProvider application={application}>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<MemoryRouter>
|
||||||
|
<LocaleProvider>
|
||||||
|
<ThemeProvider>
|
||||||
|
<SessionProvider>
|
||||||
|
<div id="portal-root" />
|
||||||
|
<main className="ui-page" style={{ padding: "1rem" }}>
|
||||||
|
<Story />
|
||||||
|
</main>
|
||||||
|
</SessionProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
</LocaleProvider>
|
||||||
|
</MemoryRouter>
|
||||||
|
</QueryClientProvider>
|
||||||
|
</ApplicationProvider>
|
||||||
|
),
|
||||||
|
],
|
||||||
|
parameters: {
|
||||||
|
a11y: {
|
||||||
|
test: "error",
|
||||||
|
},
|
||||||
|
controls: {
|
||||||
|
expanded: true,
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
storySort: {
|
||||||
|
order: ["Platform"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default preview;
|
||||||
@@ -15,4 +15,4 @@ M5 Error association: pending
|
|||||||
M6 Color signal: pending
|
M6 Color signal: pending
|
||||||
M7 Reduced motion: pending
|
M7 Reduced motion: pending
|
||||||
Screen reader: pending
|
Screen reader: pending
|
||||||
Notes: Review the text-field error association and modal focus containment/restoration.
|
Notes: Review form primitives, Menu/Tabs keyboard behavior, Toast announcements, Tooltip supplemental copy, text-field error association and modal focus containment/restoration.
|
||||||
|
|||||||
+59
-7
@@ -81,7 +81,11 @@
|
|||||||
{ "script": "check:types:fixture:application-input", "expect": "fail" },
|
{ "script": "check:types:fixture:application-input", "expect": "fail" },
|
||||||
{ "script": "check:types:fixture:async-overlay", "expect": "fail" },
|
{ "script": "check:types:fixture:async-overlay", "expect": "fail" },
|
||||||
{ "script": "check:types:fixture:route-runtime", "expect": "fail" },
|
{ "script": "check:types:fixture:route-runtime", "expect": "fail" },
|
||||||
{ "script": "check:types:fixture:page-action", "expect": "fail" }
|
{ "script": "check:types:fixture:page-action", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:icon-button", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:i18n-key", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:i18n-params", "expect": "fail" },
|
||||||
|
{ "script": "check:types:fixture:diagnostics", "expect": "fail" }
|
||||||
],
|
],
|
||||||
"logPath": "artifacts/quality/check-types.txt",
|
"logPath": "artifacts/quality/check-types.txt",
|
||||||
"evidence": ["artifacts/quality/check-types.txt"],
|
"evidence": ["artifacts/quality/check-types.txt"],
|
||||||
@@ -96,9 +100,19 @@
|
|||||||
},
|
},
|
||||||
"FE-GATE-005": {
|
"FE-GATE-005": {
|
||||||
"name": "unit",
|
"name": "unit",
|
||||||
"steps": [{ "script": "test:unit", "expect": "pass" }],
|
"steps": [
|
||||||
|
{ "script": "test:unit", "expect": "pass" },
|
||||||
|
{ "script": "test:coverage", "expect": "pass" },
|
||||||
|
{ "script": "check:coverage:fixture", "expect": "fail" }
|
||||||
|
],
|
||||||
"logPath": "artifacts/quality/gates/FE-GATE-005.txt",
|
"logPath": "artifacts/quality/gates/FE-GATE-005.txt",
|
||||||
"evidence": ["artifacts/tests/unit.xml"],
|
"evidence": [
|
||||||
|
"artifacts/tests/unit.xml",
|
||||||
|
"artifacts/tests/coverage.xml",
|
||||||
|
"artifacts/tests/coverage/coverage-summary.json",
|
||||||
|
"artifacts/quality/risk-coverage.json",
|
||||||
|
"artifacts/quality/risk-coverage-fixture.json"
|
||||||
|
],
|
||||||
"retentionClass": "merge-cycle"
|
"retentionClass": "merge-cycle"
|
||||||
},
|
},
|
||||||
"FE-GATE-006": {
|
"FE-GATE-006": {
|
||||||
@@ -123,9 +137,24 @@
|
|||||||
},
|
},
|
||||||
"FE-GATE-008": {
|
"FE-GATE-008": {
|
||||||
"name": "e2e",
|
"name": "e2e",
|
||||||
"steps": [{ "script": "test:e2e", "expect": "pass" }],
|
"steps": [
|
||||||
|
{ "script": "test:e2e", "expect": "pass" },
|
||||||
|
{ "script": "test:storybook", "expect": "pass" },
|
||||||
|
{ "script": "test:visual", "expect": "pass" },
|
||||||
|
{ "script": "check:test-evidence", "expect": "pass" },
|
||||||
|
{ "script": "check:test-evidence:fixture", "expect": "fail" }
|
||||||
|
],
|
||||||
"logPath": "artifacts/quality/gates/FE-GATE-008.txt",
|
"logPath": "artifacts/quality/gates/FE-GATE-008.txt",
|
||||||
"evidence": ["artifacts/tests/e2e/report/index.html"],
|
"evidence": [
|
||||||
|
"artifacts/tests/e2e/report/index.html",
|
||||||
|
"artifacts/tests/e2e/results.xml",
|
||||||
|
"artifacts/tests/storybook/report/index.html",
|
||||||
|
"artifacts/tests/storybook/results.xml",
|
||||||
|
"artifacts/tests/visual/report/index.html",
|
||||||
|
"artifacts/tests/visual/results.xml",
|
||||||
|
"artifacts/quality/test-evidence.json",
|
||||||
|
"artifacts/quality/test-evidence-fixture.json"
|
||||||
|
],
|
||||||
"retentionClass": "merge-cycle"
|
"retentionClass": "merge-cycle"
|
||||||
},
|
},
|
||||||
"FE-GATE-009": {
|
"FE-GATE-009": {
|
||||||
@@ -151,14 +180,33 @@
|
|||||||
"name": "architecture",
|
"name": "architecture",
|
||||||
"steps": [
|
"steps": [
|
||||||
{ "script": "check:architecture", "expect": "pass" },
|
{ "script": "check:architecture", "expect": "pass" },
|
||||||
|
{ "script": "check:design-system", "expect": "pass" },
|
||||||
|
{ "script": "check:design-system:fixture", "expect": "fail" },
|
||||||
|
{ "script": "check:i18n", "expect": "pass" },
|
||||||
|
{ "script": "check:i18n:fixture", "expect": "fail" },
|
||||||
|
{ "script": "check:diagnostics", "expect": "pass" },
|
||||||
|
{ "script": "check:diagnostics:fixture", "expect": "fail" },
|
||||||
{ "script": "check:registries", "expect": "pass" },
|
{ "script": "check:registries", "expect": "pass" },
|
||||||
|
{
|
||||||
|
"script": "check:registries:compatibility-fixtures",
|
||||||
|
"expect": "pass"
|
||||||
|
},
|
||||||
|
{ "script": "check:registries:baseline-fixture", "expect": "fail" },
|
||||||
{ "script": "check:registries:fixture", "expect": "fail" },
|
{ "script": "check:registries:fixture", "expect": "fail" },
|
||||||
{ "script": "check:routes:fixture", "expect": "fail" }
|
{ "script": "check:routes:fixture", "expect": "fail" }
|
||||||
],
|
],
|
||||||
"logPath": "artifacts/quality/gates/FE-GATE-010.txt",
|
"logPath": "artifacts/quality/gates/FE-GATE-010.txt",
|
||||||
"evidence": [
|
"evidence": [
|
||||||
"artifacts/quality/dependency-report.json",
|
"artifacts/quality/dependency-report.json",
|
||||||
|
"artifacts/quality/design-system.json",
|
||||||
|
"artifacts/quality/design-system-fixture.json",
|
||||||
|
"artifacts/quality/i18n.json",
|
||||||
|
"artifacts/quality/i18n-fixture.json",
|
||||||
|
"artifacts/quality/diagnostics.json",
|
||||||
|
"artifacts/quality/diagnostics-fixture.json",
|
||||||
"artifacts/quality/registries.json",
|
"artifacts/quality/registries.json",
|
||||||
|
"artifacts/quality/registry-compatibility-fixtures.json",
|
||||||
|
"artifacts/quality/registry-baseline-fixture.json",
|
||||||
"artifacts/quality/registry-fixture.json",
|
"artifacts/quality/registry-fixture.json",
|
||||||
"artifacts/quality/route-registry-fixture.json"
|
"artifacts/quality/route-registry-fixture.json"
|
||||||
],
|
],
|
||||||
@@ -166,11 +214,15 @@
|
|||||||
},
|
},
|
||||||
"FE-GATE-011": {
|
"FE-GATE-011": {
|
||||||
"name": "build",
|
"name": "build",
|
||||||
"steps": [{ "script": "build", "expect": "pass" }],
|
"steps": [
|
||||||
|
{ "script": "build", "expect": "pass" },
|
||||||
|
{ "script": "build:storybook", "expect": "pass" }
|
||||||
|
],
|
||||||
"logPath": "artifacts/quality/gates/FE-GATE-011.txt",
|
"logPath": "artifacts/quality/gates/FE-GATE-011.txt",
|
||||||
"evidence": [
|
"evidence": [
|
||||||
"artifacts/release/build-manifest.json",
|
"artifacts/release/build-manifest.json",
|
||||||
"artifacts/release/runtime-config.schema.json"
|
"artifacts/release/runtime-config.schema.json",
|
||||||
|
"artifacts/storybook/static/index.html"
|
||||||
],
|
],
|
||||||
"retentionClass": "release-coherence"
|
"retentionClass": "release-coherence"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"snapshotDigest": "e8448e46bc65326e9b2eb23cdce0870242faedb7a354942389c4a95b0e392d90",
|
||||||
|
"owner": "frontend-platform",
|
||||||
|
"reason": "RP-10 initial approved executable registry baseline",
|
||||||
|
"approvedAt": "2026-07-26T07:53:45.969Z"
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"changes": []
|
||||||
|
}
|
||||||
@@ -1,13 +1,46 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 2,
|
||||||
|
"sourceDirectories": [
|
||||||
|
"src/application",
|
||||||
|
"src/presentation",
|
||||||
|
"src/domain"
|
||||||
|
],
|
||||||
"registries": [
|
"registries": [
|
||||||
{
|
{
|
||||||
"registryId": "FE-REG-ROUTE",
|
"registryId": "FE-REG-ROUTE",
|
||||||
"path": "src/features/installed-feature-contracts.js",
|
"path": "src/features/installed-feature-contracts.js",
|
||||||
"exportName": "ROUTE_REGISTRY",
|
"exportName": "ROUTE_REGISTRY",
|
||||||
"owner": "feature-routing-navigation-guard-contract",
|
"owner": "feature-frontend-routing-release-recovery-runtime",
|
||||||
|
"keyField": "routeId",
|
||||||
|
"requiredFields": [
|
||||||
|
"routeId",
|
||||||
|
"path",
|
||||||
|
"paramsSchema",
|
||||||
|
"searchSchema",
|
||||||
|
"access",
|
||||||
|
"loadingSurface",
|
||||||
|
"errorSurface",
|
||||||
|
"chunkId",
|
||||||
|
"title",
|
||||||
|
"navigationLabel",
|
||||||
|
"navigationOrder"
|
||||||
|
],
|
||||||
|
"fieldTypes": {
|
||||||
|
"routeId": "string",
|
||||||
|
"path": "string",
|
||||||
|
"paramsSchema": "string|null",
|
||||||
|
"searchSchema": "string|null",
|
||||||
|
"access": "string",
|
||||||
|
"loadingSurface": "string",
|
||||||
|
"errorSurface": "string",
|
||||||
|
"chunkId": "string",
|
||||||
|
"title": "string",
|
||||||
|
"navigationLabel": "string|null",
|
||||||
|
"navigationOrder": "integer|null"
|
||||||
|
},
|
||||||
"uniqueFields": ["routeId", "path", "chunkId"],
|
"uniqueFields": ["routeId", "path", "chunkId"],
|
||||||
"allowedValues": {
|
"allowedValues": {
|
||||||
|
"access": ["public", "session-required", "integration-defined"],
|
||||||
"paramsSchema": [null, "NotFoundSplat", "ReferenceResourceParams"],
|
"paramsSchema": [null, "NotFoundSplat", "ReferenceResourceParams"],
|
||||||
"searchSchema": [null, "ReferenceResourceListQuery"],
|
"searchSchema": [null, "ReferenceResourceListQuery"],
|
||||||
"loadingSurface": [
|
"loadingSurface": [
|
||||||
@@ -23,17 +56,6 @@
|
|||||||
"route-boundary",
|
"route-boundary",
|
||||||
"feature-boundary",
|
"feature-boundary",
|
||||||
"not-found"
|
"not-found"
|
||||||
],
|
|
||||||
"chunkId": [
|
|
||||||
"route-home",
|
|
||||||
"route-examples-ui",
|
|
||||||
"route-examples-states",
|
|
||||||
"route-examples-auth",
|
|
||||||
"route-reference-resources",
|
|
||||||
"route-reference-resource-detail",
|
|
||||||
"route-reference-resource-form",
|
|
||||||
"route-reference-resource-status",
|
|
||||||
"route-not-found"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"references": [
|
"references": [
|
||||||
@@ -41,16 +63,30 @@
|
|||||||
"field": "routeId",
|
"field": "routeId",
|
||||||
"registryId": "FE-REG-ROUTE-RUNTIME",
|
"registryId": "FE-REG-ROUTE-RUNTIME",
|
||||||
"targetField": "routeId"
|
"targetField": "routeId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "paramsSchema",
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"targetField": "schemaId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "searchSchema",
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"targetField": "schemaId"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"requiredFields": [
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "src/presentation/routes/app-router.tsx",
|
||||||
|
"token": "ROUTE_REGISTRY"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": [
|
||||||
"routeId",
|
"routeId",
|
||||||
"path",
|
"path",
|
||||||
"paramsSchema",
|
"paramsSchema",
|
||||||
"searchSchema",
|
"searchSchema",
|
||||||
"access",
|
"access",
|
||||||
"loadingSurface",
|
|
||||||
"errorSurface",
|
|
||||||
"chunkId"
|
"chunkId"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -59,41 +95,56 @@
|
|||||||
"path": "src/features/installed-feature-contracts.js",
|
"path": "src/features/installed-feature-contracts.js",
|
||||||
"exportName": "ROUTE_RUNTIME_CONTRACT",
|
"exportName": "ROUTE_RUNTIME_CONTRACT",
|
||||||
"owner": "feature-frontend-routing-release-recovery-runtime",
|
"owner": "feature-frontend-routing-release-recovery-runtime",
|
||||||
|
"keyField": "routeId",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"routeId",
|
"routeId",
|
||||||
"moduleId",
|
"moduleId",
|
||||||
"paramsCodec",
|
"paramsCodec",
|
||||||
"searchCodec"
|
"searchCodec"
|
||||||
],
|
],
|
||||||
"uniqueFields": ["routeId", "moduleId"],
|
"fieldTypes": {
|
||||||
"allowedValues": {
|
"routeId": "string",
|
||||||
"moduleId": [
|
"moduleId": "string",
|
||||||
"home-page",
|
"paramsCodec": "string",
|
||||||
"ui-gallery-page",
|
"searchCodec": "string"
|
||||||
"state-gallery-page",
|
|
||||||
"auth-example-page",
|
|
||||||
"reference-resource-page",
|
|
||||||
"reference-resource-detail-page",
|
|
||||||
"reference-resource-form-page",
|
|
||||||
"reference-resource-status-page",
|
|
||||||
"not-found-page"
|
|
||||||
],
|
|
||||||
"paramsCodec": ["none", "NotFoundSplat", "ReferenceResourceParams"],
|
|
||||||
"searchCodec": ["none", "ReferenceResourceListQuery"]
|
|
||||||
},
|
},
|
||||||
|
"uniqueFields": ["routeId", "moduleId"],
|
||||||
"references": [
|
"references": [
|
||||||
{
|
{
|
||||||
"field": "routeId",
|
"field": "routeId",
|
||||||
"registryId": "FE-REG-ROUTE",
|
"registryId": "FE-REG-ROUTE",
|
||||||
"targetField": "routeId"
|
"targetField": "routeId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "paramsCodec",
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"targetField": "schemaId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "searchCodec",
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"targetField": "schemaId"
|
||||||
}
|
}
|
||||||
|
],
|
||||||
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "src/presentation/routes/route-codecs.ts",
|
||||||
|
"token": "ROUTE_RUNTIME_CONTRACT"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": [
|
||||||
|
"routeId",
|
||||||
|
"moduleId",
|
||||||
|
"paramsCodec",
|
||||||
|
"searchCodec"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"registryId": "FE-REG-API",
|
"registryId": "FE-REG-API",
|
||||||
"path": "src/features/installed-feature-contracts.js",
|
"path": "src/features/installed-feature-contracts.js",
|
||||||
"exportName": "API_OPERATIONS",
|
"exportName": "API_OPERATIONS",
|
||||||
"owner": "feature-api-client-response-envelope-contract",
|
"owner": "feature-frontend-api-client-response-envelope-contract",
|
||||||
|
"keyField": "operationId",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"method",
|
"method",
|
||||||
"path",
|
"path",
|
||||||
@@ -106,20 +157,127 @@
|
|||||||
"requestSchema",
|
"requestSchema",
|
||||||
"responseSchema",
|
"responseSchema",
|
||||||
"owner"
|
"owner"
|
||||||
|
],
|
||||||
|
"fieldTypes": {
|
||||||
|
"method": "string",
|
||||||
|
"path": "string",
|
||||||
|
"operationId": "string",
|
||||||
|
"auth": "string",
|
||||||
|
"timeoutMs": "integer|null",
|
||||||
|
"idempotency": "string",
|
||||||
|
"retry": "string",
|
||||||
|
"requestSource": "string",
|
||||||
|
"requestSchema": "string",
|
||||||
|
"responseSchema": "string",
|
||||||
|
"owner": "string"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["operationId"],
|
||||||
|
"allowedValues": {
|
||||||
|
"method": ["GET", "POST", "PUT", "PATCH", "DELETE"],
|
||||||
|
"auth": ["none", "external-session"],
|
||||||
|
"idempotency": ["safe", "keyed", "none"],
|
||||||
|
"retry": ["runtime", "never"],
|
||||||
|
"requestSource": ["none", "search", "body"]
|
||||||
|
},
|
||||||
|
"references": [
|
||||||
|
{
|
||||||
|
"field": "requestSchema",
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"targetField": "schemaId"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"field": "responseSchema",
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"targetField": "schemaId"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"consumerIdentityField": "operationId",
|
||||||
|
"consumerDirectories": [
|
||||||
|
"src/features/reference-feature/adapters",
|
||||||
|
"src/features/reference-feature/application"
|
||||||
|
],
|
||||||
|
"breakingFields": [
|
||||||
|
"method",
|
||||||
|
"path",
|
||||||
|
"operationId",
|
||||||
|
"auth",
|
||||||
|
"idempotency",
|
||||||
|
"requestSource",
|
||||||
|
"requestSchema",
|
||||||
|
"responseSchema"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"registryId": "FE-REG-SCHEMA",
|
||||||
|
"path": "src/features/installed-feature-contracts.js",
|
||||||
|
"exportName": "SCHEMA_REGISTRY",
|
||||||
|
"owner": "feature-frontend-contract-schema-registry",
|
||||||
|
"keyField": "schemaId",
|
||||||
|
"requiredFields": ["schemaId", "boundary", "owner", "runtime"],
|
||||||
|
"fieldTypes": {
|
||||||
|
"schemaId": "string",
|
||||||
|
"boundary": "string",
|
||||||
|
"owner": "string",
|
||||||
|
"runtime": "string"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["schemaId"],
|
||||||
|
"allowedValues": {
|
||||||
|
"boundary": [
|
||||||
|
"route-params",
|
||||||
|
"route-search",
|
||||||
|
"route-search-api-request",
|
||||||
|
"api-request",
|
||||||
|
"api-response"
|
||||||
|
],
|
||||||
|
"runtime": ["zod"]
|
||||||
|
},
|
||||||
|
"consumerIdentityField": "schemaId",
|
||||||
|
"consumerDirectories": [
|
||||||
|
"src/presentation/routes",
|
||||||
|
"src/features/reference-feature/presentation",
|
||||||
|
"src/features/reference-feature/contracts"
|
||||||
|
],
|
||||||
|
"breakingFields": ["schemaId", "boundary", "runtime"]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"registryId": "FE-REG-ENV",
|
"registryId": "FE-REG-ENV",
|
||||||
"path": "src/contracts/env.js",
|
"path": "src/contracts/env.js",
|
||||||
"exportName": "ENV_REGISTRY",
|
"exportName": "ENV_REGISTRY",
|
||||||
"owner": "feature-frontend-env-runtime-config-contract",
|
"owner": "feature-frontend-env-runtime-config-contract",
|
||||||
"requiredFields": ["phase", "classification", "required", "defaultValue"]
|
"requiredFields": ["phase", "classification", "required", "defaultValue"],
|
||||||
|
"fieldTypes": {
|
||||||
|
"phase": "string",
|
||||||
|
"classification": "string",
|
||||||
|
"required": "boolean",
|
||||||
|
"defaultValue": "string|integer|boolean|null"
|
||||||
|
},
|
||||||
|
"allowedValues": {
|
||||||
|
"phase": ["build", "runtime"],
|
||||||
|
"classification": [
|
||||||
|
"public",
|
||||||
|
"public-sensitive",
|
||||||
|
"public-metadata",
|
||||||
|
"compile-time"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "src/bootstrap/runtime-config-schema.js",
|
||||||
|
"token": "APP_ENV"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/contracts/env.js",
|
||||||
|
"token": "getBuildConfig"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": ["phase", "classification", "required"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"registryId": "FE-REG-STORAGE",
|
"registryId": "FE-REG-STORAGE",
|
||||||
"path": "src/contracts/storage-keys.js",
|
"path": "src/contracts/storage-keys.js",
|
||||||
"exportName": "STORAGE_REGISTRY",
|
"exportName": "STORAGE_REGISTRY",
|
||||||
"owner": "feature-frontend-storage-registry-contract",
|
"owner": "feature-frontend-storage-registry-contract",
|
||||||
|
"keyField": "logicalName",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"logicalName",
|
"logicalName",
|
||||||
"physicalKey",
|
"physicalKey",
|
||||||
@@ -129,6 +287,44 @@
|
|||||||
"ttl",
|
"ttl",
|
||||||
"migration",
|
"migration",
|
||||||
"quotaFallback"
|
"quotaFallback"
|
||||||
|
],
|
||||||
|
"fieldTypes": {
|
||||||
|
"logicalName": "string",
|
||||||
|
"physicalKey": "string",
|
||||||
|
"backend": "string",
|
||||||
|
"classification": "string",
|
||||||
|
"schemaVersion": "integer",
|
||||||
|
"ttl": "integer|string|null",
|
||||||
|
"migration": "string|function",
|
||||||
|
"quotaFallback": "string"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["logicalName", "physicalKey"],
|
||||||
|
"allowedValues": {
|
||||||
|
"backend": [
|
||||||
|
"memory",
|
||||||
|
"sessionStorage",
|
||||||
|
"localStorage",
|
||||||
|
"indexedDB",
|
||||||
|
"disabled",
|
||||||
|
"forbidden"
|
||||||
|
],
|
||||||
|
"classification": [
|
||||||
|
"public-preference",
|
||||||
|
"opaque-cache",
|
||||||
|
"sensitive-forbidden"
|
||||||
|
],
|
||||||
|
"quotaFallback": ["memory", "no-persist", "feature-disable"]
|
||||||
|
},
|
||||||
|
"consumerIdentityField": "logicalName",
|
||||||
|
"consumerDirectories": ["src", "tests"],
|
||||||
|
"orphanExemptRows": ["QUERY_PERSISTENCE", "AUTH_TOKEN"],
|
||||||
|
"breakingFields": [
|
||||||
|
"logicalName",
|
||||||
|
"physicalKey",
|
||||||
|
"backend",
|
||||||
|
"classification",
|
||||||
|
"schemaVersion",
|
||||||
|
"migration"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -136,6 +332,7 @@
|
|||||||
"path": "src/contracts/errors.js",
|
"path": "src/contracts/errors.js",
|
||||||
"exportName": "ERROR_REGISTRY",
|
"exportName": "ERROR_REGISTRY",
|
||||||
"owner": "feature-frontend-error-classification-boundary-contract",
|
"owner": "feature-frontend-error-classification-boundary-contract",
|
||||||
|
"keyField": "kind",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"kind",
|
"kind",
|
||||||
"defaultRetryable",
|
"defaultRetryable",
|
||||||
@@ -144,13 +341,41 @@
|
|||||||
"action",
|
"action",
|
||||||
"telemetryEvent",
|
"telemetryEvent",
|
||||||
"redaction"
|
"redaction"
|
||||||
]
|
],
|
||||||
|
"fieldTypes": {
|
||||||
|
"kind": "string",
|
||||||
|
"defaultRetryable": "boolean",
|
||||||
|
"severity": "string",
|
||||||
|
"userMessageKey": "string",
|
||||||
|
"action": "string",
|
||||||
|
"telemetryEvent": "string",
|
||||||
|
"redaction": "array"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["kind"],
|
||||||
|
"allowedValues": {
|
||||||
|
"severity": ["info", "warning", "error"],
|
||||||
|
"action": [
|
||||||
|
"retry",
|
||||||
|
"reauth",
|
||||||
|
"navigate",
|
||||||
|
"reload-once",
|
||||||
|
"contact-support",
|
||||||
|
"none"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "src/adapters/http/client.js",
|
||||||
|
"token": "failure("
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": ["kind", "userMessageKey", "action", "telemetryEvent"]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"registryId": "FE-REG-QUERY",
|
"registryId": "FE-REG-QUERY",
|
||||||
"path": "src/features/installed-feature-contracts.js",
|
"path": "src/features/installed-feature-contracts.js",
|
||||||
"exportName": "QUERY_REGISTRY",
|
"exportName": "QUERY_REGISTRY",
|
||||||
"owner": "feature-server-state-caching-contract",
|
"owner": "feature-frontend-server-state-caching-contract",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"namespace",
|
"namespace",
|
||||||
"serialization",
|
"serialization",
|
||||||
@@ -158,13 +383,39 @@
|
|||||||
"invalidation",
|
"invalidation",
|
||||||
"version",
|
"version",
|
||||||
"persistence"
|
"persistence"
|
||||||
|
],
|
||||||
|
"fieldTypes": {
|
||||||
|
"namespace": "array",
|
||||||
|
"serialization": "string",
|
||||||
|
"identity": "string",
|
||||||
|
"invalidation": "string",
|
||||||
|
"version": "integer",
|
||||||
|
"persistence": "string"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["namespace"],
|
||||||
|
"allowedValues": {
|
||||||
|
"persistence": ["disabled"]
|
||||||
|
},
|
||||||
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "src/features/reference-feature/contracts/reference-feature-contract.js",
|
||||||
|
"token": "referenceQueryKeys"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": [
|
||||||
|
"namespace",
|
||||||
|
"serialization",
|
||||||
|
"identity",
|
||||||
|
"version",
|
||||||
|
"persistence"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"registryId": "FE-REG-TELEMETRY",
|
"registryId": "FE-REG-TELEMETRY",
|
||||||
"path": "src/contracts/telemetry.js",
|
"path": "src/contracts/telemetry.js",
|
||||||
"exportName": "TELEMETRY_REGISTRY",
|
"exportName": "TELEMETRY_REGISTRY",
|
||||||
"owner": "feature-frontend-observability-logging-trace-contract",
|
"owner": "feature-frontend-diagnostics-telemetry-runtime",
|
||||||
|
"keyField": "eventName",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"eventName",
|
"eventName",
|
||||||
"trigger",
|
"trigger",
|
||||||
@@ -173,6 +424,31 @@
|
|||||||
"forbiddenAttributes",
|
"forbiddenAttributes",
|
||||||
"sampling",
|
"sampling",
|
||||||
"delivery"
|
"delivery"
|
||||||
|
],
|
||||||
|
"fieldTypes": {
|
||||||
|
"eventName": "string",
|
||||||
|
"trigger": "string",
|
||||||
|
"requiredAttributes": "array",
|
||||||
|
"optionalAttributes": "array",
|
||||||
|
"forbiddenAttributes": "array",
|
||||||
|
"sampling": "string",
|
||||||
|
"delivery": "string"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["eventName"],
|
||||||
|
"allowedValues": {
|
||||||
|
"delivery": ["best-effort"]
|
||||||
|
},
|
||||||
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "scripts/check-diagnostics.mjs",
|
||||||
|
"token": "TELEMETRY_REGISTRY"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": [
|
||||||
|
"eventName",
|
||||||
|
"requiredAttributes",
|
||||||
|
"forbiddenAttributes",
|
||||||
|
"delivery"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -180,11 +456,21 @@
|
|||||||
"path": "src/contracts/release-tokens.js",
|
"path": "src/contracts/release-tokens.js",
|
||||||
"exportName": "RELEASE_TOKEN_REGISTRY",
|
"exportName": "RELEASE_TOKEN_REGISTRY",
|
||||||
"owner": "feature-frontend-release-cache-rollback-contract",
|
"owner": "feature-frontend-release-cache-rollback-contract",
|
||||||
"requiredFields": ["token", "source", "compatibilityRole"]
|
"keyField": "token",
|
||||||
|
"requiredFields": ["token", "source", "compatibilityRole"],
|
||||||
|
"fieldTypes": {
|
||||||
|
"token": "string",
|
||||||
|
"source": "string",
|
||||||
|
"compatibilityRole": "string"
|
||||||
|
},
|
||||||
|
"uniqueFields": ["token"],
|
||||||
|
"consumers": [
|
||||||
|
{
|
||||||
|
"path": "src/bootstrap/load-release-manifest.js",
|
||||||
|
"token": "assetManifestHash"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"breakingFields": ["token", "source", "compatibilityRole"]
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
"compatibilityImpact": {
|
|
||||||
"allowed": ["none", "additive", "behavior-change", "breaking"],
|
|
||||||
"current": "behavior-change"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"summary": {
|
||||||
|
"lines": 80,
|
||||||
|
"statements": 78,
|
||||||
|
"functions": 85,
|
||||||
|
"branches": 68
|
||||||
|
},
|
||||||
|
"criticalModules": [
|
||||||
|
{
|
||||||
|
"path": "src/adapters/http/retry-policy.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 80,
|
||||||
|
"statements": 78,
|
||||||
|
"functions": 95,
|
||||||
|
"branches": 78
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/adapters/storage/browser-storage-adapter.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 60,
|
||||||
|
"statements": 60,
|
||||||
|
"functions": 70,
|
||||||
|
"branches": 60
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/adapters/telemetry/best-effort-telemetry.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 85,
|
||||||
|
"statements": 85,
|
||||||
|
"functions": 70,
|
||||||
|
"branches": 75
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/application/policies/compatibility.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 95,
|
||||||
|
"statements": 95,
|
||||||
|
"functions": 95,
|
||||||
|
"branches": 75
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/application/policies/performance-budgets.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 80,
|
||||||
|
"statements": 80,
|
||||||
|
"functions": 80,
|
||||||
|
"branches": 40
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/application/policies/promotion-readiness.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 95,
|
||||||
|
"statements": 95,
|
||||||
|
"functions": 95,
|
||||||
|
"branches": 95
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/application/use-cases/decide-chunk-recovery.js",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 90,
|
||||||
|
"statements": 90,
|
||||||
|
"functions": 95,
|
||||||
|
"branches": 85
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "src/contracts/diagnostics.ts",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 68,
|
||||||
|
"statements": 68,
|
||||||
|
"functions": 95,
|
||||||
|
"branches": 58
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "scripts/lib/registry-compatibility.mjs",
|
||||||
|
"minimum": {
|
||||||
|
"lines": 80,
|
||||||
|
"statements": 80,
|
||||||
|
"functions": 85,
|
||||||
|
"branches": 60
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# VD-05: Semantic icon facade와 native-first interaction
|
||||||
|
|
||||||
|
- 상태: Accepted
|
||||||
|
- 결정일: 2026-07-26
|
||||||
|
- 적용 브랜치: `feature-frontend-design-system-platform`
|
||||||
|
- 재검토: native 계약으로 충족할 수 없는 widget 요구가 확인될 때
|
||||||
|
|
||||||
|
## 배경
|
||||||
|
|
||||||
|
앱 셸과 공통 UI는 문자 glyph, raw button/select와 페이지별 focus 처리를
|
||||||
|
사용했다. 아이콘 공급자와 복합 interaction을 제품 코드에 직접 노출하면 번들,
|
||||||
|
접근성, vendor type과 교체 비용이 모든 feature로 전파된다. 반대로 실제 요구가
|
||||||
|
없는 두 개의 headless vendor를 기본 설치하면 skeleton 소비자가 제거해야 할
|
||||||
|
의존성과 중복 interaction 모델이 생긴다.
|
||||||
|
|
||||||
|
## 결정
|
||||||
|
|
||||||
|
1. 아이콘 공급자는 lockfile 최소 게시 유예를 통과한 `lucide-react@1.25.0`으로
|
||||||
|
고정한다.
|
||||||
|
2. `lucide-react`의 static named import는
|
||||||
|
`design-system/icons/vendors/lucide.tsx` 한 파일에서만 허용한다.
|
||||||
|
3. public API는 `MenuIcon`, `CloseIcon`, `WarningIcon` 같은 의미 이름만
|
||||||
|
노출한다. vendor component type, icon name, stroke API와 dynamic icon
|
||||||
|
registry는 노출하지 않는다.
|
||||||
|
4. 장식 아이콘은 accessibility tree에서 제외한다. 정보를 단독 전달하는
|
||||||
|
아이콘은 `label`, icon-only action은 필수 `accessibleName`을 사용한다.
|
||||||
|
5. 현재 복합 control은 native `dialog`, form control, `details`와 local
|
||||||
|
TypeScript state model로 구현한다. Menu는 roving focus/typeahead/Escape,
|
||||||
|
Tabs는 manual/automatic activation, Drawer는 modal/background
|
||||||
|
비활성화/focus restore 계약을 가진다.
|
||||||
|
6. React Aria와 Radix는 기본 dependency로 추가하지 않는다. native platform이
|
||||||
|
collision, nested overlay, virtualized collection 또는 복합 select 요구를
|
||||||
|
충족하지 못한다는 재현 가능한 요구가 생길 때 prototype과 ADR로 다시
|
||||||
|
평가한다.
|
||||||
|
7. Storybook과 pinned visual baseline은 VD-08/RP-10에서 도입한다. RP-07의
|
||||||
|
runtime gallery와 browser interaction test는 해당 workshop을 대체한다고
|
||||||
|
주장하지 않는다.
|
||||||
|
|
||||||
|
## 경계와 검증
|
||||||
|
|
||||||
|
- 제품 코드는 `presentation/design-system/index`만 import한다.
|
||||||
|
- design-system 검사기는 direct icon/headless import, deep import, raw palette,
|
||||||
|
undefined token과 tooltip-only required information fixture를 거절한다.
|
||||||
|
- type negative fixture는 accessible name 없는 `IconButton`을 거절한다.
|
||||||
|
- component test는 decorative icon, form control, Menu, Tabs, Drawer와 Toast를
|
||||||
|
검증한다.
|
||||||
|
- Chromium/Firefox E2E는 compact Drawer의 native modal 상태, Escape, focus
|
||||||
|
restore, gallery keyboard interaction과 axe를 검증한다.
|
||||||
|
- 로컬 WebKit 실행은 host `libevent-2.1.so.7` 부재로 환경 검증이 남아 있으며
|
||||||
|
공급자 선택이나 product behavior의 PASS로 숨기지 않는다.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
기존 `presentation/components/ui/*` 경로는 canonical TypeScript primitive를
|
||||||
|
재수출하므로 소비 코드를 즉시 되돌릴 수 있다. Lucide 제거 시 vendor facade와
|
||||||
|
semantic icon 구현만 교체하고 제품 API는 유지한다. headless vendor를 나중에
|
||||||
|
도입해도 public props와 interaction test를 유지한다.
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# VD-06: Intl과 typed local message catalog
|
||||||
|
|
||||||
|
- 상태: Accepted
|
||||||
|
- 결정일: 2026-07-26
|
||||||
|
- 적용 브랜치: `feature-frontend-i18n-message-formatting-contract`
|
||||||
|
- 재검토: 승인 locale·복수형 문법·번역 추출 workflow가 local catalog 범위를 넘을 때
|
||||||
|
|
||||||
|
## 배경
|
||||||
|
|
||||||
|
공통 셸, route surface, async/form 상태와 디자인 시스템 기본 문구가 JSX와
|
||||||
|
JavaScript에 분산돼 있었다. 날짜는 일부 application mapper에서 고정 locale로
|
||||||
|
가공되어 presentation이 locale을 바꿀 수 없었고, direction·누락 key·보간 실패
|
||||||
|
정책도 없었다. 반면 현재 skeleton에는 번역 관리 서비스, 실제 번역 승인 절차,
|
||||||
|
복잡한 ICU 문법이라는 제품 요구가 아직 없다. 이 단계에서 i18n vendor를 기본
|
||||||
|
번들에 넣으면 소비 프로젝트가 제거하거나 다시 감싸야 할 의존성만 늘어난다.
|
||||||
|
|
||||||
|
## 결정
|
||||||
|
|
||||||
|
1. 표준 `Intl.DateTimeFormat`, `NumberFormat`, `RelativeTimeFormat`,
|
||||||
|
`ListFormat`, `PluralRules`와 typed local catalog를 기본 엔진으로 사용한다.
|
||||||
|
2. `MessageKey`는 한국어 canonical catalog에서 도출하며 영어와 RTL smoke
|
||||||
|
catalog는 `satisfies Record<MessageKey, string>`으로 compile-time parity를
|
||||||
|
강제한다.
|
||||||
|
3. 보간이 필요한 key는 `MessageParameters`에 key별 parameter object를
|
||||||
|
선언한다. 잘못된 key, 누락·초과 parameter는 TypeScript negative fixture가
|
||||||
|
거절한다.
|
||||||
|
4. 기본 locale은 `ko-KR`, fallback locale도 `ko-KR`이다. 알려지지 않은 locale은
|
||||||
|
language fallback 후 `ko-KR`로 정규화한다. 알려지지 않은 key와 누락 보간은
|
||||||
|
raw key나 외부 값을 출력하지 않고 안전한 공통 fallback을 반환한다.
|
||||||
|
5. `en-XA`는 영어 문구를 확장·accent 처리하는 pseudo locale이고 `ar-EG`는
|
||||||
|
RTL 동작 smoke locale이다. 이 두 locale은 실제 제품 번역 완료를 의미하지
|
||||||
|
않는다.
|
||||||
|
6. 날짜 formatter의 기본 timezone은 테스트와 SSR/브라우저 결과가 흔들리지
|
||||||
|
않도록 `UTC`다. 제품 timezone이 필요하면 호출자가 명시한다. invalid
|
||||||
|
date/number/timezone은 `—`를 반환하고 throw하지 않는다.
|
||||||
|
7. locale state는 React inbound concern이다. `LocaleProvider`가 copy,
|
||||||
|
formatter와 `<html lang/dir>`을 제공하며 application/domain은 미리 번역된
|
||||||
|
문자열 대신 의미 값과 timestamp를 반환한다.
|
||||||
|
8. backend `message`, raw HTML, stack과 내부 key를 catalog 입력으로 신뢰하지
|
||||||
|
않는다. transport/application failure kind를 등록된 사용자 message key로
|
||||||
|
매핑한 뒤 presentation이 해석한다.
|
||||||
|
9. key rename은 즉시 제거하지 않고 `MESSAGE_KEY_ALIASES`에 compatibility alias를
|
||||||
|
둔다. alias는 새 호출의 타입에 포함하지 않아 신규 코드는 canonical key만
|
||||||
|
사용한다.
|
||||||
|
10. extraction, ICU rich message, 번역 SaaS 또는 framework adapter가 필요해지면
|
||||||
|
`presentation/i18n` public API 뒤에서 교체한다. vendor type은 feature와
|
||||||
|
design-system public prop으로 노출하지 않는다.
|
||||||
|
|
||||||
|
## 실행 경계
|
||||||
|
|
||||||
|
```text
|
||||||
|
route/form/failure 의미 값
|
||||||
|
-> presentation message key
|
||||||
|
-> LocaleProvider
|
||||||
|
-> typed catalog / Intl formatter
|
||||||
|
-> text node와 accessible name
|
||||||
|
```
|
||||||
|
|
||||||
|
- canonical catalog: `src/presentation/i18n/catalog.ts`
|
||||||
|
- feature contribution: `src/features/*/contracts/*-message-catalog.js`를
|
||||||
|
`src/features/installed-feature-messages.js`에서 조립
|
||||||
|
- key/보간/fallback/alias: `message-contract.ts`
|
||||||
|
- locale-safe value formatting: `formatters.ts`
|
||||||
|
- React composition과 document metadata: `locale-provider.tsx`
|
||||||
|
- public entry: `src/presentation/i18n/index.ts`
|
||||||
|
|
||||||
|
## 검증
|
||||||
|
|
||||||
|
- `check:i18n`은 catalog key와 placeholder parity, common UI의 한국어 literal,
|
||||||
|
backend message JSX 렌더링과 raw HTML 사용을 검사한다.
|
||||||
|
- `check:i18n:fixture`는 세 금지 사례를 실제로 거절해야 성공으로 인정된다.
|
||||||
|
- type negative fixture는 unknown key와 잘못된 parameter shape를 거절한다.
|
||||||
|
- unit test는 fallback, alias, pseudo 확장, direction과 timezone/number/relative/
|
||||||
|
list/plural/select의 결정성을 검증한다.
|
||||||
|
- component test는 document `lang/dir`, RTL Tabs와 direction-aware pagination,
|
||||||
|
Drawer semantics를 검증한다.
|
||||||
|
- Playwright는 320px pseudo reflow와 RTL compact shell/Drawer/focus restore를
|
||||||
|
Chromium, Firefox, WebKit project에서 실행한다.
|
||||||
|
|
||||||
|
## 한계와 재검토 조건
|
||||||
|
|
||||||
|
현재 catalog는 실제 번역 승인, ICU rich text, locale별 plural 문장 전체 조합,
|
||||||
|
메시지 추출/번역 메모리와 서버 locale negotiation을 제공하지 않는다. 다음 중
|
||||||
|
하나가 확인되면 별도 ADR로 엔진을 재평가한다.
|
||||||
|
|
||||||
|
- 세 개 이상의 실제 승인 locale과 번역 담당 workflow
|
||||||
|
- 복수형·성별·select가 한 문장 안에서 중첩되는 제품 copy
|
||||||
|
- server/client extraction, namespace lazy-loading 또는 번역 SaaS 연동
|
||||||
|
- SSR locale negotiation과 hydration 일치가 필요한 rendering mode
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
`ko-KR` catalog가 기존 기본 문구를 보존하므로 provider를 고정 locale adapter로
|
||||||
|
되돌려도 기본 UX를 유지한다. formatter/vendor 교체 시 public `message`,
|
||||||
|
`date`, `number`, `relativeTime`, `list`, `plural`, `select` 계약과 negative
|
||||||
|
fixture는 유지한다. alias는 migration window 종료 근거 없이 제거하지 않는다.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# VD-07: Diagnostics와 telemetry exporter 경계
|
||||||
|
|
||||||
|
- 상태: Accepted
|
||||||
|
- 결정일: 2026-07-26
|
||||||
|
- 적용 브랜치: `feature-frontend-diagnostics-telemetry-runtime`
|
||||||
|
- 재검토: 실제 운영 sink, consent가 필요한 analytics 또는 분산 tracing provider가
|
||||||
|
선정될 때
|
||||||
|
|
||||||
|
## 배경
|
||||||
|
|
||||||
|
기존 telemetry registry와 best-effort HTTP queue는 있었지만 운영 진단 record와
|
||||||
|
semantic event의 책임이 하나의 telemetry port에 섞여 있었다. boot, HTTP,
|
||||||
|
cache, storage, route와 release failure의 선언도 실제 production producer와
|
||||||
|
완전히 연결되지 않았다. 이 상태에서는 retry attempt마다 같은 사건을 발행하거나
|
||||||
|
raw URL, query, request body와 오류 객체가 queue에 들어갈 위험이 있다.
|
||||||
|
|
||||||
|
반면 skeleton 단계에는 실제 관측 vendor, endpoint의 운영 보안 정책, analytics
|
||||||
|
consent와 보존 기간이 결정되지 않았다. 특정 SDK를 기본 번들에 설치하는 것은
|
||||||
|
vendor 결정 전에는 안전한 기본값이 아니다.
|
||||||
|
|
||||||
|
## 결정
|
||||||
|
|
||||||
|
1. level 기반 운영 진단은 `DiagnosticsPort`, registry 기반 semantic event는
|
||||||
|
`TelemetryPort`로 분리한다. application은 두 port의 concrete adapter나
|
||||||
|
exporter SDK를 알지 못한다.
|
||||||
|
2. diagnostics의 level, event ID와 context key는 닫힌 registry/allowlist다.
|
||||||
|
telemetry도 event별 required/optional attribute와 value policy를 적용한다.
|
||||||
|
등록되지 않은 event·context·고카디널리티 값은 전송하지 않는다.
|
||||||
|
3. 기본 diagnostics adapter는 bounded in-memory evidence이고 telemetry는
|
||||||
|
설정이 없으면 true no-op이다. endpoint가 있을 때만 bounded oldest-drop
|
||||||
|
queue와 best-effort HTTP sink를 사용한다.
|
||||||
|
4. raw path/URL/query/body/response/storage value, credential, cookie, email,
|
||||||
|
stack과 오류 객체 전체는 context에 넣지 않는다. route ID, operation ID,
|
||||||
|
correlation ID, release ID, error kind, status/attempt/duration bucket만
|
||||||
|
허용한다.
|
||||||
|
5. HTTP logical execution은 success, retry recovery, terminal failure 또는
|
||||||
|
abort마다 `http.request.completed` diagnostics를 정확히 한 번 남긴다.
|
||||||
|
`api.request.failed` telemetry는 retry가 끝난 terminal non-abort failure에만
|
||||||
|
정확히 한 번 발행한다.
|
||||||
|
6. `app.boot.failed`, `ui.render.failed`, `release.mismatch.detected`,
|
||||||
|
`telemetry.delivery.dropped`를 production path에 연결한다. cache와 storage
|
||||||
|
실패는 diagnostics로 기록하되 raw key/value를 기록하지 않는다.
|
||||||
|
7. queue full, invalid event/context, serialization과 sink failure는 제한된
|
||||||
|
reason bucket으로 집계한다. drop observer의 failure는 다시 telemetry를
|
||||||
|
발행하지 않는 nonrecursive 경계다.
|
||||||
|
8. diagnostics와 telemetry failure는 제품 흐름, HTTP 결과, route transition,
|
||||||
|
storage/cache fallback과 React error surface를 바꾸지 않는다.
|
||||||
|
9. mount 전 bootstrap failure는 안전한 build/config/error kind만 별도 evidence로
|
||||||
|
만들며 untrusted error message, stack과 support 입력을 serialize하지 않는다.
|
||||||
|
10. 실제 error reporter, RUM, analytics나 tracing SDK는 같은 port 뒤의 외부
|
||||||
|
adapter로만 추가한다. SDK type과 event API를 application/feature/presentation
|
||||||
|
public contract에 노출하지 않는다.
|
||||||
|
|
||||||
|
## 실행 경계
|
||||||
|
|
||||||
|
```text
|
||||||
|
route/application/HTTP/cache/storage/bootstrap
|
||||||
|
-> typed DiagnosticsPort 또는 TelemetryPort
|
||||||
|
-> registry + allowlist + value policy
|
||||||
|
-> bounded memory/no-op 또는 best-effort HTTP adapter
|
||||||
|
-> 프로젝트가 선택한 외부 sink
|
||||||
|
```
|
||||||
|
|
||||||
|
- diagnostics contract: `src/contracts/diagnostics.ts`
|
||||||
|
- telemetry contract: `src/contracts/telemetry.js`
|
||||||
|
- application ports: `src/application/ports/diagnostics-port.ts`,
|
||||||
|
`telemetry-port.ts`
|
||||||
|
- bounded diagnostics: `src/adapters/diagnostics/bounded-diagnostics.ts`
|
||||||
|
- best-effort telemetry: `src/adapters/telemetry/best-effort-telemetry.js`
|
||||||
|
- composition: `src/bootstrap/runtime-adapters.js`
|
||||||
|
|
||||||
|
## 검증
|
||||||
|
|
||||||
|
- `check:diagnostics`는 모든 registry event에 production producer가 있는지와
|
||||||
|
source의 direct console/sensitive context 우회를 검사한다.
|
||||||
|
- negative source fixture는 direct console, unknown event와 raw context를 실제로
|
||||||
|
거절하며 TypeScript fixture는 잘못된 level/event ID를 거절한다.
|
||||||
|
- unit test는 allowlist, hostile/circular error, bounded diagnostics, no-op,
|
||||||
|
queue full, sink/observer failure와 pre-mount boot evidence를 검증한다.
|
||||||
|
- HTTP integration은 success, retry recovery, terminal failure와 abort의 producer
|
||||||
|
횟수, route/operation/correlation context와 요청 값 비노출을 검증한다.
|
||||||
|
- cache/storage/release/application/runtime test는 각 production wiring과
|
||||||
|
diagnostics failure isolation을 검증한다.
|
||||||
|
|
||||||
|
## 한계와 재검토 조건
|
||||||
|
|
||||||
|
기본 adapter는 운영 log 검색, source map 연계, session replay, distributed span,
|
||||||
|
analytics consent, sampling budget과 장기 보존을 제공하지 않는다. 실제 sink를
|
||||||
|
선정할 때 데이터 처리 지역, 보존 기간, consent, CSP, source map 접근 제어,
|
||||||
|
sampling과 비용 상한을 별도 결정해야 한다.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
telemetry exporter는 runtime 설정을 끄거나 adapter wiring을 `noOpTelemetry`로
|
||||||
|
바꾸어 독립적으로 제거할 수 있다. 이때도 `DiagnosticsPort`, registry,
|
||||||
|
redaction/value policy, producer-count와 negative fixture는 유지한다. 외부 SDK
|
||||||
|
문제로 application producer와 안전 계약을 함께 되돌리지 않는다.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# VD-08: 개발용 Storybook과 로컬 시각 회귀 증적
|
||||||
|
|
||||||
|
- 상태: Accepted
|
||||||
|
- 결정일: 2026-07-26
|
||||||
|
- 적용 브랜치: `feature-frontend-test-registry-evidence-hardening`
|
||||||
|
- 재검토: 제품이 cloud visual review, 다중 OS baseline 또는 별도 디자인 시스템
|
||||||
|
배포를 요구할 때
|
||||||
|
|
||||||
|
## 배경
|
||||||
|
|
||||||
|
`/examples/ui`와 `/examples/states`는 실제 application composition 안에서 공통
|
||||||
|
UI와 상태 표면을 보여 주지만, primitive를 격리해 interaction과 접근성을 검증하는
|
||||||
|
workshop은 아니었다. 실패 시 screenshot도 디버깅 증거일 뿐 의도된 UI 기준선과
|
||||||
|
현재 렌더의 차이를 차단하지 못했다.
|
||||||
|
|
||||||
|
외부 visual review 서비스, 별도 Storybook 배포와 브랜드별 baseline은 아직
|
||||||
|
선정되지 않았다. 이 결정을 기다리며 UI 회귀 검증을 비워 두거나 production
|
||||||
|
application bundle에 workshop runtime을 포함하는 것 모두 적절하지 않다.
|
||||||
|
|
||||||
|
## 결정
|
||||||
|
|
||||||
|
1. Storybook은 development dependency와 별도 static artifact로만 사용한다.
|
||||||
|
production entry와 application `dist`에는 Storybook runtime, story 또는
|
||||||
|
테스트 selector를 포함하지 않는다.
|
||||||
|
2. story는 public design-system entry를 소비하고 실제 locale, theme, session,
|
||||||
|
router와 query provider 계약으로 렌더한다. production component를 복제한
|
||||||
|
story 전용 구현을 만들지 않는다.
|
||||||
|
3. interaction과 story-level axe는 Playwright가 정적 Storybook을 대상으로
|
||||||
|
실행한다. unexpected console, page error와 request failure는 테스트 실패다.
|
||||||
|
4. 시각 회귀는 production `build` 후 `preview`를 대상으로 pinned Chromium,
|
||||||
|
locale, color scheme과 viewport에서 `toHaveScreenshot()`으로 실행한다.
|
||||||
|
5. 최초 기준선은 wide shell, compact pseudo-locale drawer, dark design-system
|
||||||
|
gallery, loading/empty/error/access 상태 표면을 포함한다.
|
||||||
|
6. animation과 caret만 결정적으로 비활성화한다. `html`, `body`, `main` 또는
|
||||||
|
application 전체를 mask해 false PASS를 만드는 설정은 gate가 거절한다.
|
||||||
|
7. snapshot 갱신은 `test:visual:update`라는 명시적 명령으로 분리하고 PNG diff를
|
||||||
|
review한다. 일반 `test:visual`은 승인 기준선을 변경하지 않는다.
|
||||||
|
8. local visual threshold는 작은 rasterization 차이만 허용하며 실제 layout,
|
||||||
|
copy, theme 또는 상태 변화가 숨겨지도록 확대하지 않는다.
|
||||||
|
9. `/examples/*`는 production composition smoke로 유지하고 Storybook story의
|
||||||
|
대체물로 취급하지 않는다. 반대로 Storybook만 통과해 application shell
|
||||||
|
integration을 완료 처리하지 않는다.
|
||||||
|
10. cloud service가 선정되지 않아도 repository-local workshop, interaction,
|
||||||
|
a11y와 visual baseline gate는 완전하게 실행 가능해야 한다.
|
||||||
|
|
||||||
|
## 실행과 증적
|
||||||
|
|
||||||
|
- workshop config: `.storybook/main.ts`, `.storybook/preview.tsx`
|
||||||
|
- story: `src/presentation/design-system/design-system.stories.tsx`
|
||||||
|
- interaction/a11y: `tests/storybook/workshop.spec.ts`
|
||||||
|
- visual: `tests/visual/platform.visual.spec.ts`
|
||||||
|
- baseline: `tests/visual/__snapshots__/`
|
||||||
|
- production E2E: `playwright.config.js`
|
||||||
|
- local dev E2E: `playwright.dev.config.js`
|
||||||
|
- evidence policy: `scripts/check-test-evidence.mjs`
|
||||||
|
|
||||||
|
CI는 JUnit, HTML report, failure trace/screenshot, visual baseline 존재 여부와
|
||||||
|
금지된 full-screen mask/무소유 skip fixture를 함께 검사한다.
|
||||||
|
|
||||||
|
## 한계와 재검토 조건
|
||||||
|
|
||||||
|
로컬 기준선은 실제 iOS/Android 기기, 여러 운영체제의 font rasterization,
|
||||||
|
디자인 승인 workflow와 다중 브랜드를 증명하지 않는다. 이를 요구하면 동일
|
||||||
|
public component와 story를 입력으로 사용하는 외부 review adapter를 추가하되,
|
||||||
|
provider 결과가 없을 때 임의 PASS로 대체하지 않는다.
|
||||||
|
|
||||||
|
## Rollback
|
||||||
|
|
||||||
|
Storybook dependency/config, workshop test와 visual config/baseline은 production
|
||||||
|
runtime 변경 없이 독립적으로 제거할 수 있다. rollback 후에도 `/examples/*`,
|
||||||
|
component behavior, automated accessibility와 built-dist E2E는 유지한다.
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
- 기본 번들에 포함할 역량과 필요할 때 설치할 확장 역량을 구분한다.
|
- 기본 번들에 포함할 역량과 필요할 때 설치할 확장 역량을 구분한다.
|
||||||
- 특정 벤더를 채택하더라도 제품 코드가 벤더 API에 직접 결합되지 않는지 확인한다.
|
- 특정 벤더를 채택하더라도 제품 코드가 벤더 API에 직접 결합되지 않는지 확인한다.
|
||||||
|
|
||||||
최초 검토 기준은 `develop`의 `cb195f8`이며, RP-01~RP-04 구현 결과를 이 문서에
|
최초 검토 기준은 `develop`의 `cb195f8`이며, RP-01~RP-10 구현 결과를 이 문서에
|
||||||
누적 반영했다. 이후 구현으로 경로나 세부 내용이 달라질 수 있으므로, 각 항목은
|
누적 반영했다. 이후 구현으로 경로나 세부 내용이 달라질 수 있으므로, 각 항목은
|
||||||
문서의 경로뿐 아니라 해당 테스트와 아키텍처 게이트로 계속 검증해야 한다.
|
문서의 경로뿐 아니라 해당 테스트와 아키텍처 게이트로 계속 검증해야 한다.
|
||||||
|
|
||||||
@@ -33,20 +33,22 @@
|
|||||||
|
|
||||||
특히 다음은 선행 해결이 필요하다.
|
특히 다음은 선행 해결이 필요하다.
|
||||||
|
|
||||||
RP-01~RP-05에서 TypeScript 도구 안전망, application runtime 주입,
|
RP-01~RP-09에서 TypeScript 도구 안전망, application runtime 주입,
|
||||||
query/mutation inbound adapter, HTTP 실행 계약과 executable route/release
|
query/mutation inbound adapter, HTTP 실행 계약과 executable route/release
|
||||||
recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다. 현재 선행 해결
|
recovery 계약, 제거 가능한 reference 수직 슬라이스, form/page, design system과
|
||||||
|
i18n 실행 경계와 diagnostics/telemetry production wiring은 구현됐다. 현재 선행 해결
|
||||||
대상은 다음과 같다.
|
대상은 다음과 같다.
|
||||||
|
|
||||||
1. 폼, 페이지 템플릿, 확장된 디자인 시스템과 컴포넌트 워크벤치
|
1. 공급망의 transitive inventory/license/vulnerability/SBOM/provenance 검증
|
||||||
2. 국제화, diagnostics, optional adapter recipe와 심화 품질 게이트
|
2. optional adapter의 opt-in 경계와 제거 가능한 recipe
|
||||||
|
|
||||||
따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다.
|
따라서 현재 상태를 “프론트 공통부가 모두 구현됐다”고 표현하면 범위가 과장된다.
|
||||||
더 정확한 표현은 다음과 같다.
|
더 정확한 표현은 다음과 같다.
|
||||||
|
|
||||||
> 운영·안전 계약과 범용 앱 셸은 갖춰졌지만, 기능 개발자가 사용하는 application
|
> application API, 서버 상태, 폼, 라우팅, 페이지, 디자인 시스템과 테스트 증적의
|
||||||
> API, 서버 상태, 폼, 라우팅, 페이지 패턴의 표준 수직 경로는 아직 보강이
|
> 표준 수직 경로는 갖춰졌다. 현재 남은 저장소 내부 범위는 공급망 검증과
|
||||||
> 필요하다.
|
> opt-in adapter recipe이며 실제 hosting·IdP·운영 provider는 프로젝트 통합
|
||||||
|
> 범위다.
|
||||||
|
|
||||||
## 3. 판정 기준
|
## 3. 판정 기준
|
||||||
|
|
||||||
@@ -65,7 +67,7 @@ recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다.
|
|||||||
| 계층 의존 방향 | 부분 준비 | `.dependency-cruiser.cjs`, `src/application/ports` | inbound/outbound 명명과 `contracts` 소유권까지 집행 |
|
| 계층 의존 방향 | 부분 준비 | `.dependency-cruiser.cjs`, `src/application/ports` | inbound/outbound 명명과 `contracts` 소유권까지 집행 |
|
||||||
| application facade | 준비됨 | typed input/output catalog, provider, production composition test | feature input use case를 contribution으로 확장 |
|
| application facade | 준비됨 | typed input/output catalog, provider, production composition test | feature input use case를 contribution으로 확장 |
|
||||||
| HTTP client | 준비됨 | path/search/body projection, runtime timeout/retry, abort/cleanup test | feature gateway 뒤에서 사용 |
|
| HTTP client | 준비됨 | path/search/body projection, runtime timeout/retry, abort/cleanup test | feature gateway 뒤에서 사용 |
|
||||||
| retry | 준비됨 | HTTP 단일 소유, runtime max attempts, Query retry off | RP-09에서 telemetry 연결 |
|
| retry | 준비됨 | HTTP 단일 소유, runtime max attempts, Query retry off, logical execution당 bounded diagnostics | terminal event 중복 방지 계약 유지 |
|
||||||
| 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper |
|
| 오류 모델 | 부분 준비 | error registry와 normalization 존재 | typed discriminated union과 계층별 mapper |
|
||||||
| 검증 | 준비됨 | runtime/API/route/form Zod parse 결과를 실행 경계에서 사용하고 domain invariant와 분리 | feature별 schema 소유권 유지 |
|
| 검증 | 준비됨 | runtime/API/route/form Zod parse 결과를 실행 경계에서 사용하고 domain invariant와 분리 | feature별 schema 소유권 유지 |
|
||||||
| 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 |
|
| 인증 연동 | 준비됨/프로젝트 선택 | opaque auth owner와 demo seam 존재 | 인증 방식별 recipe; 기본 token 저장소는 추가하지 않음 |
|
||||||
@@ -73,20 +75,20 @@ recovery 계약, 제거 가능한 reference 수직 슬라이스는 구현됐다.
|
|||||||
| 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 |
|
| 클라이언트 상태 | 부분 준비 | local state, theme context, session external store | 상태 소유권 표와 typed external-store 예제 |
|
||||||
| 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 |
|
| 범용 global store | 프로젝트 선택 | 별도 라이브러리 없음 | 필요 조건에 따라 Zustand/Redux Toolkit/state machine 선택 |
|
||||||
| 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 |
|
| 라우팅 | 준비됨 | Data Router, typed runtime map, codec, metadata consumer, bounded chunk recovery | reference feature route와 release E2E로 사용 범위 확장 |
|
||||||
| 앱 셸·반응형 | 부분 준비 | header/sidebar/content/theme 구현 | 접근 가능한 mobile drawer와 focus 복원 |
|
| 앱 셸·반응형 | 준비됨 | native modal Drawer, compact/desktop layout, Escape/link dismiss/focus restore, pseudo reflow와 RTL direction | compact browser matrix 유지 |
|
||||||
| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status slot 계약과 reference 소비 화면 | RP-07 public design-system entry로 이동 |
|
| 페이지 템플릿 | 준비됨 | Standard/Collection/Detail/Form/Status와 public design-system entry | feature별 slot 조합 유지 |
|
||||||
| 디자인 토큰 | 부분 준비 | semantic color/theme 토큰 존재 | typography, spacing, motion, layer 등 3단계 토큰 |
|
| 디자인 토큰 | 준비됨 | primitive/semantic/component CSS, 48-token 자동 계약, dark/forced-colors/reduced-motion | 제품 brand token은 외부 프로젝트에서 확장 |
|
||||||
| 공통 UI | 부분 준비 | Button, TextField, Card, Alert, Badge, Dialog | form/navigation/overlay/data/layout primitives 확장 |
|
| 공통 UI | 준비됨 | action/form/feedback/overlay/navigation primitive와 pattern, compatibility export | public story와 visual state matrix 유지 |
|
||||||
| 아이콘 | 미제공 | 문자 기호를 직접 사용 | Lucide를 로컬 icon facade 뒤에서 사용 |
|
| 아이콘 | 준비됨 | Lucide static vendor facade와 semantic icon/IconButton 접근성 계약 | 의미 icon 추가 시 bundle/접근성 기준 적용 |
|
||||||
| 폼 | 준비됨 | Zod 기반 local facade, error summary/focus, 422 allowlist, dirty/pending/conflict 정책 | 복합 form 요구가 생기면 VD-04 조건으로 vendor adapter 평가 |
|
| 폼 | 준비됨 | Zod 기반 local facade, error summary/focus, 422 allowlist, dirty/pending/conflict 정책 | 복합 form 요구가 생기면 VD-04 조건으로 vendor adapter 평가 |
|
||||||
| 국제화 | 미제공 | 한국어 문자열·locale이 하드코딩 | typed message/formatter/locale/RTL 경계 |
|
| 국제화 | 준비됨 | 137-key typed catalog, locale provider, Intl formatter, safe fallback/alias, pseudo·RTL gate | 실제 locale·번역 승인은 프로젝트에서 연결 |
|
||||||
| logging/diagnostics | 미제공 | telemetry port는 있으나 logger 없음 | redaction이 적용된 diagnostics/logging 경계 |
|
| logging/diagnostics | 준비됨 | 별도 `DiagnosticsPort`, 8-event registry, allowlist, bounded/no-op adapter와 production producer | 실제 프로젝트의 remote sink는 port 뒤에서 선택 |
|
||||||
| telemetry | 부분 준비 | registry, queue, redaction 존재 | HTTP·boot·cache·storage·route 사건에 실제 연결 |
|
| telemetry | 준비됨/프로젝트 선택 | 5-event registry, bounded queue, redaction/value policy, boot·HTTP·render·release·drop producer | analytics/RUM/error vendor와 consent는 프로젝트에서 선택 |
|
||||||
| 비동기 상태 불변식 | 준비됨 | 배타적 typed overlay, stale latch, 실제 retry/conflict action | reference 화면에서 전체 상태 전시 |
|
| 비동기 상태 불변식 | 준비됨 | 배타적 typed overlay, stale latch, 실제 retry/conflict action | reference 화면에서 전체 상태 전시 |
|
||||||
| 단위·통합·E2E | 준비됨 | Vitest, RTL, MSW, Playwright 3엔진 | TS 테스트 검사, 실제 bootstrap 통합, 위험 시나리오 보강 |
|
| 단위·통합·E2E | 준비됨 | source/test strict typecheck, shared MSW 19개 scenario, 실제 bootstrap, built-dist 3엔진·compact E2E | 제품별 critical flow를 같은 catalog/gate에 추가 |
|
||||||
| UI 회귀 검증 | 미제공 | axe/reflow는 있으나 visual baseline 없음 | Storybook 또는 동급 workshop과 시각 회귀 |
|
| UI 회귀 검증 | 준비됨 | dev-only Storybook interaction/axe와 pinned Chromium visual baseline 4종 | cloud review와 다중 OS/device는 프로젝트 선택 |
|
||||||
| 샘플 제거 | 준비됨 | feature/catalog/test 제거 후 type/architecture/registry/test/home/build 8단계 검증 | 새 contribution도 같은 제거 gate에 포함 |
|
| 샘플 제거 | 준비됨 | feature/catalog/test 제거 후 type/architecture/registry/test/home/build 9단계 검증 | 새 contribution도 같은 제거 gate에 포함 |
|
||||||
| registry·compatibility 집행 | 부분 준비 | registry와 gate는 있으나 실제 before/after 및 orphan 검사가 제한적 | type/reference/orphan/diff/migration을 자동 검증 |
|
| registry·compatibility 집행 | 준비됨 | 10개 registry type/reference/consumer/orphan, 승인 digest와 actual semantic diff, breaking evidence | public 계약 변경 시 baseline review 유지 |
|
||||||
| 공급망 검사 | 부분 준비 | lockfile·문서·gate는 있으나 실제 transitive 취약점/license/SBOM 깊이가 부족 | pinned scanner와 policy exception/증적 연결 |
|
| 공급망 검사 | 부분 준비 | lockfile·문서·gate는 있으나 실제 transitive 취약점/license/SBOM 깊이가 부족 | pinned scanner와 policy exception/증적 연결 |
|
||||||
| realtime·offline·file 등 | 프로젝트 선택 | 현재 없음 | port/adapter recipe와 선택 기준 제공 |
|
| realtime·offline·file 등 | 프로젝트 선택 | 현재 없음 | port/adapter recipe와 선택 기준 제공 |
|
||||||
|
|
||||||
@@ -216,11 +218,14 @@ guard → browser navigation adapter의 1회 reload로 연결됐다. 일반 rend
|
|||||||
failure는 이 경로에서 제외되고, 반복 실패·offline·malformed manifest·storage
|
failure는 이 경로에서 제외되고, 반복 실패·offline·malformed manifest·storage
|
||||||
실패는 지원 표면으로 fail-closed된다.
|
실패는 지원 표면으로 fail-closed된다.
|
||||||
|
|
||||||
#### telemetry, registry, 공급망 gate의 실행 깊이가 부족하다
|
#### RP-09에서 diagnostics/telemetry 실행 깊이 보강
|
||||||
|
|
||||||
telemetry registry에는 여러 사건이 있지만 실제 production producer는 제한적이다.
|
`DiagnosticsPort`와 `TelemetryPort`를 분리하고 boot, HTTP logical outcome,
|
||||||
boot, API attempt/final failure, auth recovery, storage/cache degradation, release/chunk
|
render, cache, storage, route, release mismatch와 delivery drop을 production
|
||||||
recovery를 registry 사건에 연결해야 한다.
|
producer에 연결했다. HTTP retry는 attempt별 terminal event를 발행하지 않고
|
||||||
|
logical execution 종료 시 한 번만 bounded outcome을 남긴다. allowlist와
|
||||||
|
value policy가 raw URL/query/body/storage value/error object를 거절하고 queue와
|
||||||
|
sink failure는 nonrecursive drop evidence로 제한된다.
|
||||||
|
|
||||||
registry/compatibility 검사는 다음까지 확장한다.
|
registry/compatibility 검사는 다음까지 확장한다.
|
||||||
|
|
||||||
@@ -242,7 +247,7 @@ known vulnerability, license policy, SBOM/provenance를 pinned tool로 검사해
|
|||||||
- token → primitive → pattern → template로 이어지는 디자인 시스템
|
- token → primitive → pattern → template로 이어지는 디자인 시스템
|
||||||
- Lucide를 감싼 local icon registry와 `IconButton`
|
- Lucide를 감싼 local icon registry와 `IconButton`
|
||||||
- typed message key, locale provider, formatter, pseudo-locale/RTL smoke
|
- typed message key, locale provider, formatter, pseudo-locale/RTL smoke
|
||||||
- redacted structured diagnostics/logger와 telemetry wiring
|
- RP-09에서 완료한 redacted structured diagnostics와 telemetry wiring 유지
|
||||||
- Storybook 또는 동급 isolated UI workshop
|
- Storybook 또는 동급 isolated UI workshop
|
||||||
- Playwright visual baseline, shared MSW scenarios, built-dist E2E
|
- Playwright visual baseline, shared MSW scenarios, built-dist E2E
|
||||||
- React Hooks, JSX accessibility, TanStack Query 관련 lint
|
- React Hooks, JSX accessibility, TanStack Query 관련 lint
|
||||||
@@ -250,6 +255,24 @@ known vulnerability, license policy, SBOM/provenance를 pinned tool로 검사해
|
|||||||
- registry/compatibility의 실제 diff와 orphan reference 검사
|
- registry/compatibility의 실제 diff와 orphan reference 검사
|
||||||
- transitive vulnerability, license, SBOM/provenance 공급망 gate
|
- transitive vulnerability, license, SBOM/provenance 공급망 gate
|
||||||
|
|
||||||
|
#### RP-08에서 국제화 실행 경계 구현
|
||||||
|
|
||||||
|
`src/presentation/i18n`은 shell, route, async/form error, page template와
|
||||||
|
design-system 기본 copy의 canonical 경계다. `MessageKey`와 key별
|
||||||
|
`MessageParameters`가 잘못된 key/보간을 compile time에 막고, runtime
|
||||||
|
`resolveMessage`는 unknown locale/key와 누락 보간에서 raw 값 대신 안전한
|
||||||
|
fallback을 반환한다. application mapper는 locale-formatted date를 반환하지
|
||||||
|
않고 timestamp를 유지하며 presentation formatter가 `UTC` 또는 명시 timezone을
|
||||||
|
적용한다.
|
||||||
|
|
||||||
|
`LocaleProvider`는 `ko-KR`, `en-US`, `en-XA`, `ar-EG` smoke set과 document
|
||||||
|
`lang/dir`을 동기화한다. `en-XA`는 긴 문구 reflow, `ar-EG`는 logical CSS,
|
||||||
|
Drawer, Tabs arrow와 pagination 방향 icon을 검증하기 위한 개발 locale이다.
|
||||||
|
실제 아랍어 번역 완료를 뜻하지 않는다. `check:i18n`과 negative fixture는 common
|
||||||
|
UI literal, backend raw message render와 raw HTML interpolation을 거절한다.
|
||||||
|
새 key rename은 canonical type에는 넣지 않고 runtime alias/migration window로
|
||||||
|
호환한다.
|
||||||
|
|
||||||
### 5.3 P2: 경계와 recipe를 제공할 선택 항목
|
### 5.3 P2: 경계와 recipe를 제공할 선택 항목
|
||||||
|
|
||||||
다음 기능을 모든 앱의 초기 번들에 설치할 필요는 없다. 대신 port 또는 local
|
다음 기능을 모든 앱의 초기 번들에 설치할 필요는 없다. 대신 port 또는 local
|
||||||
@@ -361,7 +384,8 @@ bootstrap → React TSX → tests 순서로 이동한다.
|
|||||||
|
|
||||||
- retry: `src/adapters/http/retry-policy.js`, 부분 준비
|
- retry: `src/adapters/http/retry-policy.js`, 부분 준비
|
||||||
- API client: `src/adapters/http/client.js`, 부분 준비
|
- API client: `src/adapters/http/client.js`, 부분 준비
|
||||||
- logger: 없음. telemetry와 분리하거나 diagnostics port로 합치는 결정 필요
|
- logger: `DiagnosticsPort`로 telemetry와 분리해 구현. closed event/level,
|
||||||
|
allowlist와 bounded/no-op adapter 제공
|
||||||
- token manager: 의도적으로 없음. opaque external auth owner가 credential을 소유
|
- token manager: 의도적으로 없음. opaque external auth owner가 credential을 소유
|
||||||
- error: `src/contracts/errors.js`와 HTTP normalization, 부분 준비
|
- error: `src/contracts/errors.js`와 HTTP normalization, 부분 준비
|
||||||
- validation: runtime/API Zod는 존재, route/form/domain 분리는 미완성
|
- validation: runtime/API Zod는 존재, route/form/domain 분리는 미완성
|
||||||
|
|||||||
@@ -588,6 +588,22 @@ RP-07은 compatibility export로 기존 primitive import를 복구할 수 있어
|
|||||||
token rename은 alias/migration 기간을 두고, vendor adapter와 local API commit을
|
token rename은 alias/migration 기간을 두고, vendor adapter와 local API commit을
|
||||||
분리한다.
|
분리한다.
|
||||||
|
|
||||||
|
**구현 증거 (2026-07-26)**
|
||||||
|
|
||||||
|
- VD-05에서 `lucide-react@1.25.0` static semantic facade와 native-first
|
||||||
|
interaction을 채택하고 headless vendor 재평가 조건을 닫았다.
|
||||||
|
- `src/presentation/design-system`이 48개 필수 token, public TypeScript barrel,
|
||||||
|
action/form/feedback/overlay/navigation primitive와 공통 pattern을 제공한다.
|
||||||
|
- 기존 `components/ui` 경로는 compatibility export로 유지하고 앱 셸, gallery와
|
||||||
|
reference feature는 public entry를 소비한다.
|
||||||
|
- 모바일 navigation은 native modal Drawer로 전환되어 배경 비활성화, Escape,
|
||||||
|
route dismiss와 trigger focus restore를 제공한다.
|
||||||
|
- source/negative fixture gate가 undefined token, raw palette, direct vendor,
|
||||||
|
deep import, tooltip-only 정보와 accessible name 누락을 거절한다.
|
||||||
|
- component/browser test가 Menu typeahead, Tabs activation, Toast queue,
|
||||||
|
form controls, compact reflow와 open-dialog axe를 실행한다. 로컬 WebKit은 host
|
||||||
|
`libevent-2.1.so.7` 부재로 환경 검증 상태를 유지한다.
|
||||||
|
|
||||||
### 08. `feature-frontend-i18n-message-formatting-contract`
|
### 08. `feature-frontend-i18n-message-formatting-contract`
|
||||||
|
|
||||||
**목표**
|
**목표**
|
||||||
@@ -635,6 +651,26 @@ token rename은 alias/migration 기간을 두고, vendor adapter와 local API co
|
|||||||
RP-08은 기존 기본 언어 catalog를 fallback으로 유지한다. 번역 catalog를
|
RP-08은 기존 기본 언어 catalog를 fallback으로 유지한다. 번역 catalog를
|
||||||
파괴적으로 덮어쓰지 않는다.
|
파괴적으로 덮어쓰지 않는다.
|
||||||
|
|
||||||
|
**구현 증거 (2026-07-26)**
|
||||||
|
|
||||||
|
- VD-06에서 dependency를 추가하지 않는 browser `Intl` + typed local catalog를
|
||||||
|
채택하고 vendor 재평가 조건, fallback과 key migration 정책을 문서화했다.
|
||||||
|
- `src/presentation/i18n`이 137개 common key, key별 interpolation,
|
||||||
|
`ko-KR` fallback, compatibility alias, date/number/relative/list/plural/select
|
||||||
|
formatter와 `LocaleProvider`를 제공한다.
|
||||||
|
- shell, route lifecycle/access/recovery, async/form error, page template와
|
||||||
|
design-system default copy가 catalog consumer로 연결됐다.
|
||||||
|
- feature route copy는 feature-owned catalog contribution으로 분리되어 reference
|
||||||
|
feature 제거 시 source와 built artifact에 전용 message key가 남지 않는다.
|
||||||
|
- reference application mapper는 locale-formatted date 대신 timestamp를
|
||||||
|
반환하고 presentation formatter가 UTC 또는 명시 timezone을 적용한다.
|
||||||
|
- `check:i18n`과 type negative fixture가 catalog/placeholder 불일치,
|
||||||
|
hardcoded common literal, backend raw message render, unsafe HTML,
|
||||||
|
unknown key와 interpolation mismatch를 거절한다.
|
||||||
|
- unit/component/browser test가 safe fallback, pseudo 320px reflow,
|
||||||
|
document `lang/dir`, RTL Drawer/Tabs/directional icon과 deterministic formatter를
|
||||||
|
검증한다.
|
||||||
|
|
||||||
### 09. `feature-frontend-diagnostics-telemetry-runtime`
|
### 09. `feature-frontend-diagnostics-telemetry-runtime`
|
||||||
|
|
||||||
**목표**
|
**목표**
|
||||||
@@ -687,6 +723,28 @@ render와 release 사건을 실제 producer에 연결한다.
|
|||||||
RP-09는 exporter를 제거하고 즉시 no-op adapter로 전환할 수 있어야 한다.
|
RP-09는 exporter를 제거하고 즉시 no-op adapter로 전환할 수 있어야 한다.
|
||||||
diagnostics port와 redaction test는 유지한다.
|
diagnostics port와 redaction test는 유지한다.
|
||||||
|
|
||||||
|
**구현 증거 (2026-07-26)**
|
||||||
|
|
||||||
|
- VD-07에서 level/event 기반 `DiagnosticsPort`와 semantic `TelemetryPort`를
|
||||||
|
분리하고 bounded memory/no-op 또는 설정 기반 best-effort HTTP exporter를
|
||||||
|
채택했다.
|
||||||
|
- diagnostics 8종과 telemetry 5종의 registry, context/attribute allowlist,
|
||||||
|
고카디널리티 value policy, timestamp와 status/attempt/duration/queue bucket을
|
||||||
|
구현했다.
|
||||||
|
- boot, route, render, HTTP logical outcome, cache, storage, release mismatch와
|
||||||
|
telemetry drop을 production composition에 연결했다. HTTP는 success/recovery/
|
||||||
|
terminal/abort 각각 logical execution당 diagnostics 한 번, terminal
|
||||||
|
non-abort failure telemetry 한 번만 발행한다.
|
||||||
|
- bounded oldest-drop queue, drop reason 집계, sink/observer failure 격리와
|
||||||
|
nonrecursive delivery evidence를 구현했다. exporter가 없으면 network와 queue
|
||||||
|
side effect가 없는 true no-op이다.
|
||||||
|
- `check:diagnostics`, source negative fixture와 TypeScript negative fixture가
|
||||||
|
producer 누락, direct console, unknown event/context, raw URL/query/body/
|
||||||
|
credential 경계를 거절한다.
|
||||||
|
- unit/integration test가 circular/hostile error, pre-mount boot, queue/sink
|
||||||
|
failure, no-op, cache/storage/release producer, success/retry recovery/terminal/
|
||||||
|
abort 횟수와 reference route/operation/correlation context를 검증한다.
|
||||||
|
|
||||||
### 10. `feature-frontend-test-registry-evidence-hardening`
|
### 10. `feature-frontend-test-registry-evidence-hardening`
|
||||||
|
|
||||||
**목표**
|
**목표**
|
||||||
@@ -750,6 +808,35 @@ RP-10은 직전 승인 registry snapshot과 test evidence다. flaky visual/brows
|
|||||||
infrastructure commit은 product behavior와 분리한다. 장기 skip으로 PASS하지 않고
|
infrastructure commit은 product behavior와 분리한다. 장기 skip으로 PASS하지 않고
|
||||||
owner와 만료 시한이 있는 quarantine만 허용한다.
|
owner와 만료 시한이 있는 quarantine만 허용한다.
|
||||||
|
|
||||||
|
**구현 증거 (2026-07-26)**
|
||||||
|
|
||||||
|
- VD-08에서 dev-only Storybook static workshop과 production build를 대상으로 한
|
||||||
|
local Playwright visual baseline을 채택하고 cloud review는 선택 사항으로
|
||||||
|
분리했다.
|
||||||
|
- 10개 registry의 required field, runtime type, enum, unique, cross-reference,
|
||||||
|
consumer와 orphan을 검사하고 승인 snapshot digest와 현재 snapshot의 actual
|
||||||
|
semantic diff를 계산한다. 행·field·type·path뿐 아니라 registry 검증 계약
|
||||||
|
변경도 breaking evidence 대상이다.
|
||||||
|
- ordering-only 변경은 `none`, row addition은 `additive`, 일반 값 변경은
|
||||||
|
`behavior-change`, 제거/type/path/contract 변경은 `breaking`으로 계산한다.
|
||||||
|
breaking에는 version, migration, compatibility window, rollback과 owner를
|
||||||
|
요구하며 digest 변조와 누락 fixture가 실제로 실패한다.
|
||||||
|
- API operation별 19개 shared MSW scenario catalog와 strict unhandled-request
|
||||||
|
server를 제공하고 reference vertical integration이 공통 envelope/handler를
|
||||||
|
사용한다.
|
||||||
|
- 기본 Playwright는 `build` + `preview`의 실제 `dist`를 Chromium, Firefox,
|
||||||
|
WebKit에서 검사하고 별도 compact project를 제공한다. 개발 피드백용 Vite
|
||||||
|
profile은 `playwright.dev.config.js`로 분리했다.
|
||||||
|
- Storybook public primitive story, interaction과 axe test, wide/compact/
|
||||||
|
pseudo/dark/state surface의 pinned Chromium visual baseline 4종을 CI evidence로
|
||||||
|
연결했다.
|
||||||
|
- V8 coverage와 9개 high-risk module을 대상으로 40개 scoped threshold를
|
||||||
|
적용하고 threshold 미달 fixture를 차단한다.
|
||||||
|
- deterministic clock/random/scheduler/storage, unexpected console/page error/
|
||||||
|
request failure 정책, 무소유 skip과 full-screen mask 금지 gate를 제공한다.
|
||||||
|
- JUnit, HTML report, trace/screenshot, coverage, registry와 fixture artifact를
|
||||||
|
기존 26개 blocking gate taxonomy에 연결했다.
|
||||||
|
|
||||||
### 11. `feature-frontend-supply-chain-verification`
|
### 11. `feature-frontend-supply-chain-verification`
|
||||||
|
|
||||||
**목표**
|
**목표**
|
||||||
|
|||||||
@@ -171,6 +171,22 @@ query vendor import는 architecture gate가 거절한다. reference feature의
|
|||||||
list/detail/create/status route가 각각 Collection/Detail/Form/Status template의
|
list/detail/create/status route가 각각 Collection/Detail/Form/Status template의
|
||||||
실제 consumer다.
|
실제 consumer다.
|
||||||
|
|
||||||
|
RP-07에서 React inbound adapter 안의 UI 공급자 경계도 닫혔다.
|
||||||
|
`src/presentation/design-system/index.ts`는 token → primitive → pattern →
|
||||||
|
template public API이며 feature와 shell은 이 entry만 소비한다. Lucide는
|
||||||
|
`icons/vendors/lucide.tsx`에 격리된 inbound vendor facade이므로 application
|
||||||
|
port가 아니다. native Dialog/Drawer/Menu/Tabs의 focus·keyboard 상태도
|
||||||
|
presentation이 소유하고 use case나 outbound adapter로 올리지 않는다.
|
||||||
|
|
||||||
|
RP-08에서 i18n은 application output port가 아니라 React inbound adapter의
|
||||||
|
local facade로 확정됐다. domain/application은 locale이나 번역 문장을 알지 않고
|
||||||
|
timestamp, number, failure kind 같은 의미 값만 반환한다.
|
||||||
|
`src/presentation/i18n`이 typed message catalog, formatter, fallback,
|
||||||
|
`<html lang/dir>`과 pseudo/RTL smoke를 소유한다. backend raw `message`는
|
||||||
|
application failure registry를 우회해 렌더링할 수 없으며 `check:i18n` negative
|
||||||
|
fixture가 이 경계를 집행한다. 번역 vendor를 나중에 선택해도 이 facade 뒤의
|
||||||
|
adapter만 교체한다.
|
||||||
|
|
||||||
이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한
|
이 문서의 목표 구조는 기존 기반을 폐기하는 것이 아니라 이러한
|
||||||
불일치를 제거하는 것이다.
|
불일치를 제거하는 것이다.
|
||||||
|
|
||||||
@@ -763,22 +779,31 @@ Logger와 telemetry는 같은 것이 아니다.
|
|||||||
- Telemetry: registry에 정의된 semantic event와 metric
|
- Telemetry: registry에 정의된 semantic event와 metric
|
||||||
- Error reporter: 예외 집계와 release correlation
|
- Error reporter: 예외 집계와 release correlation
|
||||||
|
|
||||||
기본 `Logger` output port는 safe context만 받는다.
|
VD-07에 따라 기본 구현은 임의 message 문자열을 받는 `Logger`가 아니라 닫힌
|
||||||
|
event ID와 safe context만 받는 `DiagnosticsPort`다.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
export interface Logger {
|
export interface DiagnosticsPort {
|
||||||
debug(message: string, context?: SafeLogContext): void;
|
record(input: {
|
||||||
info(message: string, context?: SafeLogContext): void;
|
level: DiagnosticLevel;
|
||||||
warn(message: string, context?: SafeLogContext): void;
|
eventId: DiagnosticEventId;
|
||||||
error(message: string, context?: SafeLogContext): void;
|
context?: DiagnosticContext;
|
||||||
|
}): void;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
개발 환경에는 redacted console adapter, production에는 allowlist 기반
|
기본 runtime에는 bounded in-memory diagnostics와 설정 기반 best-effort
|
||||||
remote adapter, 테스트에는 recording 또는 no-op adapter를 연결한다.
|
telemetry adapter, 테스트에는 recording 또는 no-op adapter를 연결한다.
|
||||||
|
direct `console`은 redaction 경계를 우회하므로 source gate가 거절한다.
|
||||||
민감정보 redaction은 각 호출자의 선의가 아니라 adapter와 contract에서
|
민감정보 redaction은 각 호출자의 선의가 아니라 adapter와 contract에서
|
||||||
강제한다.
|
강제한다.
|
||||||
|
|
||||||
|
현재 production producer는 boot, logical HTTP outcome, cache, storage, route,
|
||||||
|
render, release mismatch와 telemetry delivery drop을 포함한다. HTTP terminal
|
||||||
|
telemetry는 모든 retry가 끝난 뒤 한 번만 발행하며 abort에는 발행하지 않는다.
|
||||||
|
raw path/query/body/error 대신 route/operation/correlation ID와
|
||||||
|
status/attempt/duration bucket만 전달한다.
|
||||||
|
|
||||||
## 16. Feature 경계와 removable reference feature
|
## 16. Feature 경계와 removable reference feature
|
||||||
|
|
||||||
Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야
|
Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야
|
||||||
@@ -1207,9 +1232,10 @@ contract와 실패 분기를 우선한다.
|
|||||||
- [ ] runtime timeout/retry 설정이 실제 HTTP transport에 반영된다.
|
- [ ] runtime timeout/retry 설정이 실제 HTTP transport에 반영된다.
|
||||||
- [ ] QueryClient와 feature query bridge가 실제 route에서 동작한다.
|
- [ ] QueryClient와 feature query bridge가 실제 route에서 동작한다.
|
||||||
- [ ] session UI API와 credential attachment가 분리되어 있다.
|
- [ ] session UI API와 credential attachment가 분리되어 있다.
|
||||||
- [ ] logger와 telemetry가 HTTP/render/storage/cache failure 경로에
|
- [x] diagnostics와 telemetry가 HTTP/render/storage/cache failure 경로에
|
||||||
연결된다.
|
연결된다.
|
||||||
- [ ] page lifecycle에서 필요한 telemetry flush/cleanup이 수행된다.
|
- [x] `pagehide`에서 bounded telemetry queue를 flush하고 adapter `dispose`가
|
||||||
|
lifecycle listener를 정리한다.
|
||||||
|
|
||||||
### 26.3 HTTP와 validation
|
### 26.3 HTTP와 validation
|
||||||
|
|
||||||
|
|||||||
@@ -447,6 +447,13 @@ controller가 소유하지 않는 것:
|
|||||||
| Page Template | 반복 layout/state | 접근성과 반응형 구조 재사용 | data fetching을 template에 포함 |
|
| Page Template | 반복 layout/state | 접근성과 반응형 구조 재사용 | data fetching을 template에 포함 |
|
||||||
| Registry + Runtime Map | route/operation/event | 선언과 실행 완전성 | 모든 설정을 하나의 거대 전역 파일에 집중 |
|
| Registry + Runtime Map | route/operation/event | 선언과 실행 완전성 | 모든 설정을 하나의 거대 전역 파일에 집중 |
|
||||||
|
|
||||||
|
RP-08 이후 route contract의 `title`/`navigation` 필드는 fallback metadata이며
|
||||||
|
실제 document title, navigation, loading/error/access surface는
|
||||||
|
`route.<ROUTE_ID>.title|navigation` typed catalog key를 해석한다. route params,
|
||||||
|
search, backend message를 translation key로 조립하지 않는다. locale 변경은
|
||||||
|
현재 route를 재요청하거나 query key를 바꾸지 않고 document title과 화면 copy만
|
||||||
|
다시 렌더링한다.
|
||||||
|
|
||||||
패턴은 추상화 파일만 만든 것으로 완료되지 않는다. reference usage, negative
|
패턴은 추상화 파일만 만든 것으로 완료되지 않는다. reference usage, negative
|
||||||
architecture test, 실패 상태 test가 있어야 제공된 패턴으로 본다.
|
architecture test, 실패 상태 test가 있어야 제공된 패턴으로 본다.
|
||||||
|
|
||||||
|
|||||||
@@ -468,23 +468,57 @@ raw response body, stack, token, URL query, PII를 사용자 copy나 일반 log
|
|||||||
|
|
||||||
### 7.3 diagnostics와 telemetry
|
### 7.3 diagnostics와 telemetry
|
||||||
|
|
||||||
현재 telemetry event contract와 별도로 개발·진단용 structured logger가 필요하다.
|
VD-07에서 level/event 기반 `DiagnosticsPort`와 semantic
|
||||||
다음 두 설계 중 하나를 ADR로 결정한다.
|
`TelemetryPort`를 분리했다. diagnostics는 8개 event ID와 safe context
|
||||||
|
allowlist를, telemetry는 event별 required/optional attribute와 value policy를
|
||||||
1. `DiagnosticsPort`가 log/event/span을 내부 method로 구분
|
사용한다.
|
||||||
2. `LoggerPort`와 `TelemetryPort`를 분리
|
|
||||||
|
|
||||||
공통 요구:
|
공통 요구:
|
||||||
|
|
||||||
- log level과 event key는 닫힌 union
|
- log level과 event key는 닫힌 union
|
||||||
- attribute allowlist와 중앙 redaction
|
- attribute allowlist와 중앙 redaction
|
||||||
- dev adapter는 console을 사용하되 동일 redaction 적용
|
- 기본 adapter는 bounded memory/no-op이고 endpoint가 있을 때만 best-effort
|
||||||
- production adapter는 provider SDK를 감싸며 앱 코드는 SDK를 import하지 않음
|
HTTP queue를 사용
|
||||||
|
- production provider SDK를 추가할 때도 port 뒤에서 감싸며 앱 코드는 SDK를
|
||||||
|
import하지 않음
|
||||||
- 오류 객체 전체를 그대로 serialize하지 않음
|
- 오류 객체 전체를 그대로 serialize하지 않음
|
||||||
- trace ID/build ID/route ID/operation ID를 허용된 범위에서 연결
|
- trace ID/build ID/route ID/operation ID를 허용된 범위에서 연결
|
||||||
- logging failure가 제품 flow를 실패시키지 않음
|
- logging failure가 제품 flow를 실패시키지 않음
|
||||||
- consent가 필요한 analytics와 essential diagnostics를 분리
|
- consent가 필요한 analytics와 essential diagnostics를 분리
|
||||||
|
|
||||||
|
HTTP는 route/operation/correlation ID를 logical execution context로 생성하고
|
||||||
|
success/recovered/failed/aborted 종료 시 diagnostics를 한 번만 기록한다.
|
||||||
|
terminal non-abort failure만 telemetry를 한 번 발행한다. cache/storage와 boot
|
||||||
|
producer는 raw key, value, message, stack을 버리고 error kind와 bounded
|
||||||
|
operation만 남긴다. queue full과 sink failure는 제한된 reason bucket이며 drop
|
||||||
|
observer가 실패해도 재귀 발행하지 않는다.
|
||||||
|
|
||||||
|
### 7.4 locale, message와 표시 값
|
||||||
|
|
||||||
|
RP-08부터 locale은 presentation-owned React context다. server/application
|
||||||
|
state에 번역된 문자열을 저장하거나 query key에 locale을 넣는 것은 응답 자체가
|
||||||
|
locale별 데이터인 경우에만 허용한다. 공통 UI copy 변경 때문에 query cache를
|
||||||
|
복제하지 않는다.
|
||||||
|
|
||||||
|
```text
|
||||||
|
API timestamp/number/failure kind
|
||||||
|
-> schema + mapper (의미 값 유지)
|
||||||
|
-> application result
|
||||||
|
-> presentation controller
|
||||||
|
-> useLocale().date/number/message
|
||||||
|
```
|
||||||
|
|
||||||
|
- message key는 `MessageKey` union이며 interpolation은 key별 tuple type이다.
|
||||||
|
- unknown external key는 `resolveMessage`에 전달해도 raw key가 표시되지 않는다.
|
||||||
|
- backend `message`는 diagnostic input일 수 있지만 사용자 copy가 아니다.
|
||||||
|
- form validation code는 `ParameterlessMessageKey` allowlist로 mapping한다.
|
||||||
|
- date의 기본 timezone은 UTC이고 제품 timezone은 presentation 호출자가
|
||||||
|
명시한다.
|
||||||
|
- pseudo/RTL locale state는 local interaction state이며 persistence와 server
|
||||||
|
synchronization을 기본 제공하지 않는다.
|
||||||
|
- key rename은 typed canonical key를 먼저 이동하고 runtime alias에 migration
|
||||||
|
기간을 둔다.
|
||||||
|
|
||||||
## 8. 폼 표준
|
## 8. 폼 표준
|
||||||
|
|
||||||
VD-04에 따라 현재 기본 엔진은 React native form event와 controlled value이며
|
VD-04에 따라 현재 기본 엔진은 React native form event와 controlled value이며
|
||||||
@@ -584,4 +618,5 @@ backend message와 알 수 없는 path는 field copy로 사용하지 않는다.
|
|||||||
- 상태 종류별 소유권이 테스트와 문서에서 확인된다.
|
- 상태 종류별 소유권이 테스트와 문서에서 확인된다.
|
||||||
- token은 UI와 일반 storage/store에 노출되지 않는다.
|
- token은 UI와 일반 storage/store에 노출되지 않는다.
|
||||||
- failure와 validation의 각 계층이 typed mapper로 분리된다.
|
- failure와 validation의 각 계층이 typed mapper로 분리된다.
|
||||||
|
- common UI copy, locale formatter와 direction이 typed i18n facade를 통과한다.
|
||||||
- query/mutation/form recipe만으로 새 기능을 만들 수 있다.
|
- query/mutation/form recipe만으로 새 기능을 만들 수 있다.
|
||||||
|
|||||||
@@ -47,23 +47,23 @@
|
|||||||
- Chromium, Firefox, WebKit
|
- Chromium, Firefox, WebKit
|
||||||
- 등록 라우트의 자동 접근성 검사
|
- 등록 라우트의 자동 접근성 검사
|
||||||
|
|
||||||
이 기반은 유효하지만 아직 디자인 시스템 플랫폼 전체는 아니다.
|
RP-07 구현 이후 이 기반은 저장소 내부 디자인 시스템 플랫폼 계약을 충족한다.
|
||||||
|
아래 목록은 구현 전 공백과 현재 해결 상태를 함께 보존한다.
|
||||||
|
|
||||||
1. 토큰이 색상 중심이며 typography, elevation, motion, z-layer, control size,
|
1. typography, elevation, motion, z-layer, control size와 breakpoint는
|
||||||
breakpoint가 계약으로 닫혀 있지 않다.
|
`design-system/tokens`의 3계층과 자동 gate로 닫혔다.
|
||||||
2. RP-06 form/page foundation은 준비됐지만 TextArea, Select, Checkbox,
|
2. RP-06 form/page foundation은 준비됐지만 TextArea, Select, Checkbox,
|
||||||
RadioGroup 같은 form primitive 확장은 RP-07에 남아 있다.
|
RadioGroup 같은 form primitive 확장은 RP-07에 남아 있다.
|
||||||
3. 앱 셸과 예제 화면에서 공용 primitive 대신 raw `button`, `select`, 링크
|
3. 앱 셸, 예제와 reference feature는 public design-system barrel을 소비한다.
|
||||||
class를 다시 작성하는 곳이 있다.
|
4. 문자 glyph는 semantic Lucide facade로 교체됐다.
|
||||||
4. `☰`, `×` 같은 문자 glyph를 직접 사용하며 아이콘 공급자 경계가 없다.
|
5. token은 세 CSS 파일로 분리됐고 `theme.css`는 layout/component styling만
|
||||||
5. `theme.css` 하나가 token, layout, primitive, pattern 스타일을 모두 소유한다.
|
소유한다.
|
||||||
6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이
|
6. runtime gallery는 있지만 격리된 story, interaction story, 시각 회귀 기준선이
|
||||||
없다.
|
없다.
|
||||||
7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다.
|
7. 사용자 문구가 한국어 literal로 고정되어 locale과 RTL 계약이 없다.
|
||||||
8. page template은 준비됐지만 RP-07 design-system public entry와 token/pattern
|
8. page template, form과 pattern은 public barrel에서 제공된다.
|
||||||
계층으로 정리해야 한다.
|
9. 모바일 navigation은 native modal Drawer로 focus 이동, 배경 비활성화,
|
||||||
9. 모바일 sidebar는 표시 전환은 되지만 modal drawer 수준의 focus 이동, focus
|
Escape/link dismiss와 trigger focus restore를 제공한다.
|
||||||
복원, 배경 비활성화 계약은 없다.
|
|
||||||
|
|
||||||
따라서 기존 구성요소는 폐기하지 않고 아래 목표 계층으로 이동·확장한다.
|
따라서 기존 구성요소는 폐기하지 않고 아래 목표 계층으로 이동·확장한다.
|
||||||
|
|
||||||
@@ -534,8 +534,9 @@ Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다.
|
|||||||
|
|
||||||
## 9. 국제화 계약
|
## 9. 국제화 계약
|
||||||
|
|
||||||
디자인 시스템 primitive는 한국어 문구를 내부 기본값으로 숨기지 않는다.
|
RP-08에서 디자인 시스템 primitive의 닫기, alert, toast, 글자 수 같은 기본
|
||||||
접근성 label이나 오류 문구가 필요하면 명시적인 prop 또는 message key를 받는다.
|
문구는 `useLocale()` typed catalog로 이동했다. 제품 의미를 가진 label은 여전히
|
||||||
|
명시적인 prop으로 받으며 primitive가 feature message key를 소유하지 않는다.
|
||||||
|
|
||||||
필수 국제화 기반:
|
필수 국제화 기반:
|
||||||
|
|
||||||
@@ -551,6 +552,17 @@ Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다.
|
|||||||
- pseudo-locale
|
- pseudo-locale
|
||||||
- RTL story와 E2E smoke
|
- RTL story와 E2E smoke
|
||||||
|
|
||||||
|
현재 구현 위치와 실패 정책:
|
||||||
|
|
||||||
|
- `presentation/i18n/catalog.ts`: 137개 canonical common key와 locale parity
|
||||||
|
- `message-contract.ts`: key별 interpolation, fallback과 compatibility alias
|
||||||
|
- `formatters.ts`: UTC-default date, number, relative time, list, plural/select
|
||||||
|
- `locale-provider.tsx`: document `lang/dir`과 React consumer API
|
||||||
|
- missing key/parameter와 formatter 예외: 빈 문자열이나 raw key 대신 안전한
|
||||||
|
fallback
|
||||||
|
- `en-XA`: 긴 문자열/320px reflow, `ar-EG`: logical layout/RTL keyboard smoke
|
||||||
|
- backend raw message와 translated HTML: 정적 negative gate에서 거절
|
||||||
|
|
||||||
금지 패턴:
|
금지 패턴:
|
||||||
|
|
||||||
- 번역 문장 중간에 JSX 문자열을 연결한다.
|
- 번역 문장 중간에 JSX 문자열을 연결한다.
|
||||||
@@ -559,7 +571,7 @@ Radix는 overlay와 primitive composition을 중심으로 평가할 수 있다.
|
|||||||
- route title, navigation label, toast message를 JSX literal로 분산한다.
|
- route title, navigation label, toast message를 JSX literal로 분산한다.
|
||||||
- 번역 누락 시 빈 문자열을 렌더링한다.
|
- 번역 누락 시 빈 문자열을 렌더링한다.
|
||||||
|
|
||||||
Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어야 한다.
|
RP-10의 Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어야 한다.
|
||||||
|
|
||||||
- `ko-KR`, light
|
- `ko-KR`, light
|
||||||
- `en-US`, light
|
- `en-US`, light
|
||||||
|
|||||||
@@ -43,7 +43,12 @@
|
|||||||
- `test:unit`
|
- `test:unit`
|
||||||
- `test:component`
|
- `test:component`
|
||||||
- `test:integration`
|
- `test:integration`
|
||||||
|
- `test:coverage`
|
||||||
- `test:e2e`
|
- `test:e2e`
|
||||||
|
- `test:e2e:dev`
|
||||||
|
- `build:storybook`
|
||||||
|
- `test:storybook`
|
||||||
|
- `test:visual`
|
||||||
- `test:a11y`
|
- `test:a11y`
|
||||||
- `review:a11y-manual`
|
- `review:a11y-manual`
|
||||||
- `test:sample-removal`
|
- `test:sample-removal`
|
||||||
@@ -67,7 +72,7 @@ field/documentation 단계를 구성한다.
|
|||||||
- 320px reflow와 mobile navigation을 E2E로 확인한다.
|
- 320px reflow와 mobile navigation을 E2E로 확인한다.
|
||||||
- release build의 bundle과 lab performance budget이 별도 gate다.
|
- release build의 bundle과 lab performance budget이 별도 gate다.
|
||||||
|
|
||||||
### 2.3 확인된 공백
|
### 2.3 RP-10에서 닫힌 공백과 남은 외부 범위
|
||||||
|
|
||||||
#### 테스트 TypeScript typecheck 기반
|
#### 테스트 TypeScript typecheck 기반
|
||||||
|
|
||||||
@@ -76,20 +81,12 @@ field/documentation 단계를 구성한다.
|
|||||||
검사하되 실패를 의도한 `tests/fixtures`는 별도 negative command가 소유한다.
|
검사하되 실패를 의도한 `tests/fixtures`는 별도 negative command가 소유한다.
|
||||||
Vitest의 변환 성공을 TypeScript typecheck의 대체물로 취급하지 않는다.
|
Vitest의 변환 성공을 TypeScript typecheck의 대체물로 취급하지 않는다.
|
||||||
|
|
||||||
#### 실제 bootstrap integration test가 없다
|
#### 실제 bootstrap integration
|
||||||
|
|
||||||
`tests/component/bootstrap-shell.test.jsx`는 production bootstrap을 import하지
|
runtime config와 release manifest를 검증한 composition root에서 실제 provider
|
||||||
않고 테스트 내부의 `<TestShell>`만 렌더링한다. E2E는 실제 entry를 통과하지만,
|
순서와 application input을 연결하는 component/integration test를 제공한다.
|
||||||
다음 실패를 작은 통합 테스트에서 식별하기 어렵다.
|
production Playwright profile은 source fixture가 아니라 `build` + `preview`의
|
||||||
|
실제 entry와 hashed route chunk를 사용한다.
|
||||||
- runtime config fetch 실패
|
|
||||||
- config/manifest mismatch
|
|
||||||
- adapter composition 실패
|
|
||||||
- provider 순서 또는 누락
|
|
||||||
- external auth owner 유무
|
|
||||||
- product tree를 마운트하기 전 fail-closed
|
|
||||||
- boot error shell의 safe metadata
|
|
||||||
- StrictMode와 unmount cleanup
|
|
||||||
|
|
||||||
#### TanStack Query의 React integration test 기반
|
#### TanStack Query의 React integration test 기반
|
||||||
|
|
||||||
@@ -100,53 +97,44 @@ optimistic commit/rollback, conflict 해제와 namespace invalidation이 실제
|
|||||||
QueryClient 위에서 실행된다. HTTP 자동 retry가 소유자이므로 이 adapter의
|
QueryClient 위에서 실행된다. HTTP 자동 retry가 소유자이므로 이 adapter의
|
||||||
query/mutation vendor retry는 꺼져 있다.
|
query/mutation vendor retry는 꺼져 있다.
|
||||||
|
|
||||||
#### Form 테스트가 단일 TextField 흐름에 머문다
|
#### Form과 route 위험
|
||||||
|
|
||||||
현재 component/E2E는 label, description, error association과 빈 값 submit을
|
form component/reference feature test가 error summary, 첫 오류 focus, Zod
|
||||||
검사한다. error summary, 첫 오류 focus, async validation race, 422 field error,
|
transform, 422 allowlist, double submit, dirty navigation, optimistic rollback과
|
||||||
double submit, dirty navigation, mutation conflict는 없다.
|
conflict를 검증한다. route registry/runtime 양방향 참조, codec, lazy module,
|
||||||
|
location reset, scroll restoration, blocker와 bounded chunk recovery도
|
||||||
|
unit/component/built artifact 검증에 연결됐다.
|
||||||
|
|
||||||
#### Route registry와 실행 tree가 별도로 테스트된다
|
#### Storybook과 시각 회귀
|
||||||
|
|
||||||
registry snapshot과 일부 navigation/access policy test는 있으나 다음 계약을
|
public design-system primitive를 실제 platform provider로 렌더하는 dev-only
|
||||||
강제하지 않는다.
|
Storybook, interaction/axe test와 production build를 대상으로 한
|
||||||
|
`toHaveScreenshot()` baseline 4종을 제공한다. cloud review, 다중 OS font
|
||||||
|
rasterization과 실제 device farm은 프로젝트가 요구할 때 연결한다.
|
||||||
|
|
||||||
- 모든 route ID에 lazy runtime module이 존재하는가
|
#### Shared MSW와 결정성
|
||||||
- params/search가 실제 codec으로 검증되는가
|
|
||||||
- deep link와 basename refresh가 동작하는가
|
|
||||||
- chunk load failure가 1회 reload/support surface로 연결되는가
|
|
||||||
- route error boundary가 location 변경 시 reset되는가
|
|
||||||
- scroll restoration과 form navigation blocker가 동작하는가
|
|
||||||
|
|
||||||
#### Storybook과 시각 회귀가 없다
|
operation별 success/empty/slow/network/timeout/content/envelope/schema/auth/
|
||||||
|
403/404/409/422/429/retry/terminal을 포함한 19개 scenario catalog와 strict
|
||||||
|
unhandled-request server를 공유한다. clock/random/scheduler/storage helper와
|
||||||
|
browser console/page/network failure 정책으로 비결정적 우회를 차단한다.
|
||||||
|
|
||||||
`/examples/ui`는 통합 gallery지만 component별 모든 state를 격리하지 않는다.
|
#### Built-dist와 compact E2E
|
||||||
Storybook story, interaction story, story-level axe, `toHaveScreenshot()` baseline이
|
|
||||||
없다. `screenshot: "only-on-failure"`는 디버깅 증거이며 시각 회귀 테스트가 아니다.
|
|
||||||
|
|
||||||
#### MSW scenario가 공유되지 않는다
|
기본 `test:e2e`는 CI에서 기존 server를 재사용하지 않고 `build` + `preview`를
|
||||||
|
Chromium, Firefox, WebKit과 compact project로 실행한다. 빠른 Vite 개발 profile은
|
||||||
|
`test:e2e:dev`로 분리한다.
|
||||||
|
|
||||||
integration file마다 `setupServer`, handler, response body를 다시 정의한다.
|
#### 위험 기반 coverage
|
||||||
Node integration, Storybook browser, feature component test, E2E mock service가 같은
|
|
||||||
시나리오 이름과 contract fixture를 공유하지 않는다.
|
|
||||||
|
|
||||||
#### E2E가 개발 서버를 대상으로 한다
|
V8 text/JSON/LCOV를 생성하고 전체 기준과 retry/storage/telemetry/compatibility/
|
||||||
|
performance/promotion/chunk/diagnostics/registry compatibility 9개 high-risk
|
||||||
|
module에 40개 scoped threshold를 적용한다. critical module 누락 또는 threshold
|
||||||
|
미달 fixture는 merge gate를 실패시킨다.
|
||||||
|
|
||||||
현재 Playwright web server는 `pnpm dev`다. route behavior 확인에는 유효하지만
|
남은 범위는 실제 device/browser farm, cloud visual approval, 외부 인증·telemetry
|
||||||
다음 release 위험은 production build/preview에서만 확인할 수 있다.
|
provider와 production field data다. 이 증거가 없을 때 저장소 내부 test를
|
||||||
|
`PRODUCTION_READY`의 대체물로 사용하지 않는다.
|
||||||
- hashed lazy chunk
|
|
||||||
- source 변환과 tree shaking
|
|
||||||
- base path
|
|
||||||
- deep-link fallback
|
|
||||||
- build-time environment
|
|
||||||
- release manifest와 runtime config 조합
|
|
||||||
- minified code의 chunk failure
|
|
||||||
|
|
||||||
#### Coverage가 실행·차단되지 않는다
|
|
||||||
|
|
||||||
`vitest.config.js`에는 reporter만 선언되어 있고 coverage provider, script,
|
|
||||||
threshold, diff policy가 없다.
|
|
||||||
|
|
||||||
## 3. 위험 기반 테스트 계층
|
## 3. 위험 기반 테스트 계층
|
||||||
|
|
||||||
@@ -410,6 +398,8 @@ Page / AsyncSurface / Form pattern
|
|||||||
- filter 순서가 달라도 canonical key가 같다.
|
- filter 순서가 달라도 canonical key가 같다.
|
||||||
- route unmount 또는 superseded input에서 request를 abort한다.
|
- route unmount 또는 superseded input에서 request를 abort한다.
|
||||||
- aborted request는 terminal error나 telemetry failure로 오분류되지 않는다.
|
- aborted request는 terminal error나 telemetry failure로 오분류되지 않는다.
|
||||||
|
- success와 retry recovery는 terminal failure telemetry를 만들지 않고,
|
||||||
|
exhausted retry는 logical execution당 한 번만 발행한다.
|
||||||
- offline/paused와 loading을 구분한다.
|
- offline/paused와 loading을 구분한다.
|
||||||
- 401 복구는 한 번만 수행한다.
|
- 401 복구는 한 번만 수행한다.
|
||||||
- 재로그인 후 허용된 operation만 다시 실행한다.
|
- 재로그인 후 허용된 operation만 다시 실행한다.
|
||||||
@@ -562,6 +552,30 @@ client route guard는 UX이며 authorization이 아님을 test 이름과 문서
|
|||||||
|
|
||||||
공용 컴포넌트는 한 번의 결함이 모든 페이지로 전파되므로 위험도가 높다.
|
공용 컴포넌트는 한 번의 결함이 모든 페이지로 전파되므로 위험도가 높다.
|
||||||
|
|
||||||
|
RP-07의 실행 경로는 `check:design-system`,
|
||||||
|
`check:design-system:fixture`, `check:types:fixture:icon-button`,
|
||||||
|
`tests/component/design-system-platform.test.tsx`와
|
||||||
|
`tests/e2e/design-system-interactions.spec.js`다. Story interaction/visual
|
||||||
|
baseline은 VD-08/RP-10에서 추가하며 현재 runtime gallery를 isolated workshop
|
||||||
|
완료 증거로 사용하지 않는다.
|
||||||
|
|
||||||
|
RP-08의 국제화 실행 경로는 `check:i18n`, `check:i18n:fixture`,
|
||||||
|
`check:types:fixture:i18n-key`, `check:types:fixture:i18n-params`,
|
||||||
|
`tests/unit/i18n-contract.test.ts`, `tests/component/locale-platform.test.tsx`와
|
||||||
|
`tests/e2e/i18n.spec.js`다.
|
||||||
|
|
||||||
|
- unit: locale catalog/placeholder parity, safe fallback/alias, pseudo expansion,
|
||||||
|
direction과 UTC date/number/relative/list/plural/select
|
||||||
|
- component: document `lang/dir`, RTL tab arrow semantics, direction-aware
|
||||||
|
pagination과 modal Drawer
|
||||||
|
- E2E: 320px pseudo reflow와 compact RTL shell/Drawer/focus restore
|
||||||
|
- negative: common UI locale literal, backend message JSX render, raw translated
|
||||||
|
HTML, unknown key와 잘못된 interpolation parameter
|
||||||
|
|
||||||
|
`ar-EG` catalog가 영어 smoke copy를 재사용하는 것은 RTL behavior 검증용이며
|
||||||
|
번역 품질 PASS가 아니다. 실제 locale catalog에는 언어 담당 승인 evidence가
|
||||||
|
추가되어야 한다.
|
||||||
|
|
||||||
### 10.1 Component behavior
|
### 10.1 Component behavior
|
||||||
|
|
||||||
- native role/name/value
|
- native role/name/value
|
||||||
@@ -1202,8 +1216,9 @@ corepack pnpm build
|
|||||||
corepack pnpm check:bundle
|
corepack pnpm check:bundle
|
||||||
```
|
```
|
||||||
|
|
||||||
TypeScript test, Storybook, coverage, visual, built-dist 명령이 도입되면 위 목록과
|
TypeScript test, Storybook, coverage, visual과 built-dist 명령은
|
||||||
CI registry에 추가한다.
|
`config/ci/gates.json`의 blocking step과 JUnit/HTML/trace/fixture evidence에
|
||||||
|
연결되어 있다.
|
||||||
|
|
||||||
## 18. Feature Definition of Done
|
## 18. Feature Definition of Done
|
||||||
|
|
||||||
@@ -1259,7 +1274,8 @@ CI registry에 추가한다.
|
|||||||
- [ ] high-risk module branch 목표를 충족한다.
|
- [ ] high-risk module branch 목표를 충족한다.
|
||||||
- [ ] 신규 코드의 미검증 branch에 승인 없는 예외가 없다.
|
- [ ] 신규 코드의 미검증 branch에 승인 없는 예외가 없다.
|
||||||
- [ ] bundle/performance budget을 통과한다.
|
- [ ] bundle/performance budget을 통과한다.
|
||||||
- [ ] telemetry/error output에 민감 정보가 없다.
|
- [x] diagnostics/telemetry output의 allowlist, value policy와 negative fixture가
|
||||||
|
raw URL/query/body/storage value/error object를 거절한다.
|
||||||
- [ ] 관련 gate와 evidence registry가 갱신되었다.
|
- [ ] 관련 gate와 evidence registry가 갱신되었다.
|
||||||
|
|
||||||
## 19. 금지 패턴
|
## 19. 금지 패턴
|
||||||
|
|||||||
@@ -76,6 +76,8 @@ export default [
|
|||||||
"artifacts/**",
|
"artifacts/**",
|
||||||
"tests/fixtures/typecheck/**",
|
"tests/fixtures/typecheck/**",
|
||||||
"tests/fixtures/architecture/forbidden/**",
|
"tests/fixtures/architecture/forbidden/**",
|
||||||
|
"tests/fixtures/diagnostics/forbidden/**",
|
||||||
|
"tests/fixtures/i18n/forbidden/**",
|
||||||
"tests/fixtures/security/forbidden/**",
|
"tests/fixtures/security/forbidden/**",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -115,6 +117,25 @@ export default [
|
|||||||
"no-unused-vars": "off",
|
"no-unused-vars": "off",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
files: ["**/*.d.ts"],
|
||||||
|
languageOptions: {
|
||||||
|
...commonLanguageOptions,
|
||||||
|
parser: babelParser,
|
||||||
|
parserOptions: {
|
||||||
|
requireConfigFile: false,
|
||||||
|
babelOptions: {
|
||||||
|
plugins: [
|
||||||
|
["@babel/plugin-syntax-typescript", { dts: true }],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
"no-undef": "off",
|
||||||
|
"no-unused-vars": "off",
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
files: ["**/*.tsx"],
|
files: ["**/*.tsx"],
|
||||||
languageOptions: {
|
languageOptions: {
|
||||||
@@ -272,6 +293,12 @@ export default [
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
files: [`tests/support/browser/**/*.${sourceExtensions}`],
|
||||||
|
rules: {
|
||||||
|
"react-hooks/rules-of-hooks": "off",
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
files: [
|
files: [
|
||||||
`tests/fixtures/architecture/forbidden/**/*.${sourceExtensions}`,
|
`tests/fixtures/architecture/forbidden/**/*.${sourceExtensions}`,
|
||||||
|
|||||||
+29
-1
@@ -13,8 +13,14 @@
|
|||||||
"build": "vite build && node scripts/generate-build-manifest.mjs",
|
"build": "vite build && node scripts/generate-build-manifest.mjs",
|
||||||
"build:release": "corepack pnpm build && corepack pnpm generate:supply-chain && corepack pnpm scan:security",
|
"build:release": "corepack pnpm build && corepack pnpm generate:supply-chain && corepack pnpm scan:security",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"lint": "eslint src scripts tests vite.config.js vitest.config.js playwright.config.js --max-warnings=0",
|
"lint": "eslint src scripts tests .storybook vite.config.js vitest.config.js playwright*.config.js --max-warnings=0",
|
||||||
"check:architecture": "node scripts/check-architecture.mjs",
|
"check:architecture": "node scripts/check-architecture.mjs",
|
||||||
|
"check:design-system": "node scripts/check-design-system.mjs",
|
||||||
|
"check:design-system:fixture": "node scripts/check-design-system.mjs --fixture",
|
||||||
|
"check:i18n": "node scripts/check-i18n.mjs",
|
||||||
|
"check:i18n:fixture": "node scripts/check-i18n.mjs --fixture",
|
||||||
|
"check:diagnostics": "node scripts/check-diagnostics.mjs",
|
||||||
|
"check:diagnostics:fixture": "node scripts/check-diagnostics.mjs --fixture",
|
||||||
"check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test",
|
"check:types": "corepack pnpm check:types:app && corepack pnpm check:types:node && corepack pnpm check:types:test",
|
||||||
"check:types:app": "tsc --project tsconfig.app.json",
|
"check:types:app": "tsc --project tsconfig.app.json",
|
||||||
"check:types:node": "tsc --project tsconfig.node.json",
|
"check:types:node": "tsc --project tsconfig.node.json",
|
||||||
@@ -27,21 +33,38 @@
|
|||||||
"check:types:fixture:async-overlay": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts",
|
"check:types:fixture:async-overlay": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-async-overlay.ts",
|
||||||
"check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts",
|
"check:types:fixture:route-runtime": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-route-runtime.ts",
|
||||||
"check:types:fixture:page-action": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx",
|
"check:types:fixture:page-action": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-page-action.tsx",
|
||||||
|
"check:types:fixture:icon-button": "tsc --ignoreConfig --allowJs --checkJs --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler --jsx react-jsx tests/fixtures/typecheck/invalid-icon-button.tsx",
|
||||||
|
"check:types:fixture:i18n-key": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-key.ts",
|
||||||
|
"check:types:fixture:i18n-params": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-message-params.ts",
|
||||||
|
"check:types:fixture:diagnostics": "tsc --ignoreConfig --strict --noEmit --skipLibCheck --target ES2022 --module ESNext --moduleResolution Bundler tests/fixtures/typecheck/invalid-diagnostics-port.ts",
|
||||||
"test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests",
|
"test:runtime-schema": "vitest run tests/runtime-schema --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/runtime-schema.xml --passWithNoTests",
|
||||||
"test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml",
|
"test:unit": "vitest run tests/unit --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/unit.xml",
|
||||||
"test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml",
|
"test:component": "vitest run tests/component --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/component.xml",
|
||||||
"test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml",
|
"test:integration": "vitest run tests/integration --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/integration.xml",
|
||||||
"test:e2e": "playwright test",
|
"test:e2e": "playwright test",
|
||||||
|
"test:e2e:dev": "playwright test --config playwright.dev.config.js",
|
||||||
|
"storybook": "storybook dev -p 6006",
|
||||||
|
"build:storybook": "storybook build -o artifacts/storybook/static",
|
||||||
|
"test:storybook": "playwright test --config playwright.storybook.config.js",
|
||||||
|
"test:visual": "playwright test --config playwright.visual.config.js",
|
||||||
|
"test:visual:update": "playwright test --config playwright.visual.config.js --update-snapshots",
|
||||||
|
"check:test-evidence": "node scripts/check-test-evidence.mjs",
|
||||||
|
"check:test-evidence:fixture": "node scripts/check-test-evidence.mjs --source-root tests/fixtures/test-evidence/forbidden --artifact artifacts/quality/test-evidence-fixture.json",
|
||||||
"test:a11y": "playwright test --grep @a11y && node scripts/write-a11y-report.mjs",
|
"test:a11y": "playwright test --grep @a11y && node scripts/write-a11y-report.mjs",
|
||||||
"review:a11y-manual": "node scripts/verify-a11y-manual.mjs",
|
"review:a11y-manual": "node scripts/verify-a11y-manual.mjs",
|
||||||
"test:sample-removal": "node scripts/test-sample-removal.mjs",
|
"test:sample-removal": "node scripts/test-sample-removal.mjs",
|
||||||
"test:reference-feature": "vitest run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests",
|
"test:reference-feature": "vitest run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests",
|
||||||
|
"test:coverage": "vitest run tests/runtime-schema tests/unit tests/component tests/integration tests/features/reference-feature --coverage --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.mjs",
|
||||||
|
"check:coverage:fixture": "node scripts/check-risk-coverage.mjs --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json",
|
||||||
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature",
|
"test:all": "corepack pnpm test:runtime-schema && corepack pnpm test:unit && corepack pnpm test:component && corepack pnpm test:integration && corepack pnpm test:reference-feature",
|
||||||
"verify:lockfile": "corepack pnpm install --frozen-lockfile",
|
"verify:lockfile": "corepack pnpm install --frozen-lockfile",
|
||||||
"generate:supply-chain": "node scripts/generate-supply-chain.mjs",
|
"generate:supply-chain": "node scripts/generate-supply-chain.mjs",
|
||||||
"scan:security": "node scripts/security-scan.mjs",
|
"scan:security": "node scripts/security-scan.mjs",
|
||||||
"check:browser-security": "node scripts/check-browser-security.mjs",
|
"check:browser-security": "node scripts/check-browser-security.mjs",
|
||||||
"check:registries": "node scripts/check-registries.mjs",
|
"check:registries": "node scripts/check-registries.mjs",
|
||||||
|
"check:registries:structure": "node scripts/check-registries.mjs --no-baseline",
|
||||||
|
"check:registries:compatibility-fixtures": "node scripts/check-registry-compatibility-fixtures.mjs",
|
||||||
|
"check:registries:baseline-fixture": "node scripts/check-registries.mjs --approval tests/fixtures/registry/compatibility/tampered-approval.json --artifact artifacts/quality/registry-baseline-fixture.json",
|
||||||
"check:registries:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/forbidden/governance.json --artifact artifacts/quality/registry-fixture.json",
|
"check:registries:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/forbidden/governance.json --artifact artifacts/quality/registry-fixture.json",
|
||||||
"check:routes:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/routes/governance.json --artifact artifacts/quality/route-registry-fixture.json",
|
"check:routes:fixture": "node scripts/check-registries.mjs --governance tests/fixtures/registry/routes/governance.json --artifact artifacts/quality/route-registry-fixture.json",
|
||||||
"verify:compatibility": "node scripts/check-compatibility.mjs",
|
"verify:compatibility": "node scripts/check-compatibility.mjs",
|
||||||
@@ -58,6 +81,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tanstack/react-query": "5.101.4",
|
"@tanstack/react-query": "5.101.4",
|
||||||
|
"lucide-react": "1.25.0",
|
||||||
"react": "19.2.8",
|
"react": "19.2.8",
|
||||||
"react-dom": "19.2.8",
|
"react-dom": "19.2.8",
|
||||||
"react-router-dom": "7.18.1",
|
"react-router-dom": "7.18.1",
|
||||||
@@ -71,6 +95,8 @@
|
|||||||
"@babel/plugin-syntax-typescript": "8.0.3",
|
"@babel/plugin-syntax-typescript": "8.0.3",
|
||||||
"@eslint/js": "10.0.1",
|
"@eslint/js": "10.0.1",
|
||||||
"@playwright/test": "1.62.0",
|
"@playwright/test": "1.62.0",
|
||||||
|
"@storybook/addon-a11y": "10.5.4",
|
||||||
|
"@storybook/react-vite": "10.5.4",
|
||||||
"@tailwindcss/vite": "4.3.3",
|
"@tailwindcss/vite": "4.3.3",
|
||||||
"@testing-library/jest-dom": "7.0.0",
|
"@testing-library/jest-dom": "7.0.0",
|
||||||
"@testing-library/react": "16.3.2",
|
"@testing-library/react": "16.3.2",
|
||||||
@@ -79,12 +105,14 @@
|
|||||||
"@types/react": "19.2.8",
|
"@types/react": "19.2.8",
|
||||||
"@types/react-dom": "19.2.3",
|
"@types/react-dom": "19.2.3",
|
||||||
"@vitejs/plugin-react": "6.0.4",
|
"@vitejs/plugin-react": "6.0.4",
|
||||||
|
"@vitest/coverage-v8": "4.1.10",
|
||||||
"dependency-cruiser": "18.1.0",
|
"dependency-cruiser": "18.1.0",
|
||||||
"eslint": "10.8.0",
|
"eslint": "10.8.0",
|
||||||
"eslint-plugin-react-hooks": "7.1.1",
|
"eslint-plugin-react-hooks": "7.1.1",
|
||||||
"globals": "17.7.0",
|
"globals": "17.7.0",
|
||||||
"jsdom": "29.1.1",
|
"jsdom": "29.1.1",
|
||||||
"msw": "2.15.0",
|
"msw": "2.15.0",
|
||||||
|
"storybook": "10.5.4",
|
||||||
"tailwindcss": "4.3.3",
|
"tailwindcss": "4.3.3",
|
||||||
"typescript": "7.0.2",
|
"typescript": "7.0.2",
|
||||||
"vite": "8.1.5",
|
"vite": "8.1.5",
|
||||||
|
|||||||
+31
-7
@@ -6,20 +6,44 @@ export default defineConfig({
|
|||||||
reporter: [
|
reporter: [
|
||||||
["list"],
|
["list"],
|
||||||
["html", { outputFolder: "./artifacts/tests/e2e/report", open: "never" }],
|
["html", { outputFolder: "./artifacts/tests/e2e/report", open: "never" }],
|
||||||
|
["junit", { outputFile: "./artifacts/tests/e2e/results.xml" }],
|
||||||
],
|
],
|
||||||
use: {
|
use: {
|
||||||
baseURL: "http://127.0.0.1:5173",
|
baseURL: "http://127.0.0.1:4173",
|
||||||
trace: "retain-on-failure",
|
trace: "retain-on-failure",
|
||||||
screenshot: "only-on-failure",
|
screenshot: "only-on-failure",
|
||||||
},
|
},
|
||||||
webServer: {
|
webServer: {
|
||||||
command: "corepack pnpm dev --host 127.0.0.1",
|
command:
|
||||||
url: "http://127.0.0.1:5173",
|
"corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port 4173",
|
||||||
reuseExistingServer: !process.env.CI,
|
url: "http://127.0.0.1:4173",
|
||||||
|
reuseExistingServer: false,
|
||||||
},
|
},
|
||||||
projects: [
|
projects: [
|
||||||
{ name: "chromium", use: { ...devices["Desktop Chrome"] } },
|
{
|
||||||
{ name: "firefox", use: { ...devices["Desktop Firefox"] } },
|
name: "chromium",
|
||||||
{ name: "webkit", use: { ...devices["Desktop Safari"] } },
|
testIgnore: "**/compact-smoke.spec.js",
|
||||||
|
use: { ...devices["Desktop Chrome"] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "firefox",
|
||||||
|
testIgnore: "**/compact-smoke.spec.js",
|
||||||
|
use: { ...devices["Desktop Firefox"] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "webkit",
|
||||||
|
testIgnore: "**/compact-smoke.spec.js",
|
||||||
|
use: { ...devices["Desktop Safari"] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "chromium-compact",
|
||||||
|
testMatch: "**/compact-smoke.spec.js",
|
||||||
|
use: {
|
||||||
|
...devices["Desktop Chrome"],
|
||||||
|
viewport: { width: 390, height: 844 },
|
||||||
|
hasTouch: true,
|
||||||
|
isMobile: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { defineConfig } from "@playwright/test";
|
||||||
|
|
||||||
|
import releaseConfig from "./playwright.config.js";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
...releaseConfig,
|
||||||
|
use: {
|
||||||
|
...releaseConfig.use,
|
||||||
|
baseURL: "http://127.0.0.1:5173",
|
||||||
|
},
|
||||||
|
webServer: {
|
||||||
|
command: "corepack pnpm dev --host 127.0.0.1",
|
||||||
|
url: "http://127.0.0.1:5173",
|
||||||
|
reuseExistingServer: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./tests/storybook",
|
||||||
|
outputDir: "./artifacts/tests/storybook/results",
|
||||||
|
reporter: [
|
||||||
|
["list"],
|
||||||
|
[
|
||||||
|
"html",
|
||||||
|
{
|
||||||
|
outputFolder: "./artifacts/tests/storybook/report",
|
||||||
|
open: "never",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"junit",
|
||||||
|
{ outputFile: "./artifacts/tests/storybook/results.xml" },
|
||||||
|
],
|
||||||
|
],
|
||||||
|
use: {
|
||||||
|
baseURL: "http://127.0.0.1:6006",
|
||||||
|
trace: "retain-on-failure",
|
||||||
|
screenshot: "only-on-failure",
|
||||||
|
},
|
||||||
|
webServer: {
|
||||||
|
command:
|
||||||
|
"corepack pnpm build:storybook && node scripts/serve-static.mjs artifacts/storybook/static 6006",
|
||||||
|
url: "http://127.0.0.1:6006",
|
||||||
|
reuseExistingServer: false,
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{ name: "chromium-workshop", use: { ...devices["Desktop Chrome"] } },
|
||||||
|
],
|
||||||
|
});
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./tests/visual",
|
||||||
|
snapshotDir: "./tests/visual/__snapshots__",
|
||||||
|
outputDir: "./artifacts/tests/visual/results",
|
||||||
|
reporter: [
|
||||||
|
["list"],
|
||||||
|
[
|
||||||
|
"html",
|
||||||
|
{ outputFolder: "./artifacts/tests/visual/report", open: "never" },
|
||||||
|
],
|
||||||
|
["junit", { outputFile: "./artifacts/tests/visual/results.xml" }],
|
||||||
|
],
|
||||||
|
expect: {
|
||||||
|
toHaveScreenshot: {
|
||||||
|
animations: "disabled",
|
||||||
|
caret: "hide",
|
||||||
|
maxDiffPixelRatio: 0.002,
|
||||||
|
scale: "css",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
use: {
|
||||||
|
...devices["Desktop Chrome"],
|
||||||
|
baseURL: "http://127.0.0.1:4174",
|
||||||
|
colorScheme: "light",
|
||||||
|
locale: "en-US",
|
||||||
|
trace: "retain-on-failure",
|
||||||
|
},
|
||||||
|
webServer: {
|
||||||
|
command:
|
||||||
|
"corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port 4174",
|
||||||
|
url: "http://127.0.0.1:4174",
|
||||||
|
reuseExistingServer: false,
|
||||||
|
},
|
||||||
|
projects: [{ name: "chromium-visual" }],
|
||||||
|
});
|
||||||
Generated
+1482
-16
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,5 @@
|
|||||||
allowBuilds:
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
msw: true
|
msw: true
|
||||||
minimumReleaseAgeExclude:
|
minimumReleaseAgeExclude:
|
||||||
- '@playwright/test@1.62.0'
|
- '@playwright/test@1.62.0'
|
||||||
|
|||||||
@@ -4,24 +4,49 @@
|
|||||||
"required": [
|
"required": [
|
||||||
"schemaVersion",
|
"schemaVersion",
|
||||||
"generatedAt",
|
"generatedAt",
|
||||||
"compatibilityImpact",
|
"baselineDigest",
|
||||||
|
"currentDigest",
|
||||||
|
"compatibility",
|
||||||
"failures",
|
"failures",
|
||||||
"registries"
|
"registries"
|
||||||
],
|
],
|
||||||
"properties": {
|
"properties": {
|
||||||
"schemaVersion": { "const": 1 },
|
"schemaVersion": { "const": 2 },
|
||||||
"generatedAt": { "type": "string", "format": "date-time" },
|
"generatedAt": { "type": "string", "format": "date-time" },
|
||||||
"compatibilityImpact": {
|
"baselineDigest": {
|
||||||
"enum": ["none", "additive", "behavior-change", "breaking"]
|
"type": "string",
|
||||||
|
"pattern": "^[a-f0-9]{64}$"
|
||||||
|
},
|
||||||
|
"currentDigest": {
|
||||||
|
"type": "string",
|
||||||
|
"pattern": "^[a-f0-9]{64}$"
|
||||||
|
},
|
||||||
|
"compatibility": {
|
||||||
|
"type": "object",
|
||||||
|
"required": ["impact", "changes"],
|
||||||
|
"properties": {
|
||||||
|
"impact": {
|
||||||
|
"enum": ["none", "additive", "behavior-change", "breaking"]
|
||||||
|
},
|
||||||
|
"changes": { "type": "array" }
|
||||||
|
},
|
||||||
|
"additionalProperties": false
|
||||||
},
|
},
|
||||||
"failures": { "type": "array", "maxItems": 0 },
|
"failures": { "type": "array", "maxItems": 0 },
|
||||||
"registries": {
|
"registries": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"minItems": 8,
|
"minItems": 10,
|
||||||
"maxItems": 8,
|
"maxItems": 10,
|
||||||
"items": {
|
"items": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": ["registryId", "owner", "source", "rowCount", "rows"]
|
"required": [
|
||||||
|
"registryId",
|
||||||
|
"owner",
|
||||||
|
"source",
|
||||||
|
"rowCount",
|
||||||
|
"contract",
|
||||||
|
"rows"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// @ts-expect-error Node 24 executes erasable TypeScript for this build-time gate.
|
||||||
|
import { REQUIRED_COMPONENT_TOKENS, REQUIRED_PRIMITIVE_TOKENS, REQUIRED_SEMANTIC_TOKENS } from "../src/presentation/design-system/tokens/token-contract.ts";
|
||||||
|
|
||||||
|
const fixtureMode = process.argv.includes("--fixture");
|
||||||
|
const failures = [];
|
||||||
|
const tokenFiles = {
|
||||||
|
primitive: "src/presentation/design-system/tokens/primitive.css",
|
||||||
|
semantic: "src/presentation/design-system/tokens/semantic.css",
|
||||||
|
component: "src/presentation/design-system/tokens/component.css",
|
||||||
|
};
|
||||||
|
/** @type {Array<readonly [string, string, readonly string[]]>} */
|
||||||
|
const tokenLayers = [
|
||||||
|
["primitive", tokenFiles.primitive, REQUIRED_PRIMITIVE_TOKENS],
|
||||||
|
["semantic", tokenFiles.semantic, REQUIRED_SEMANTIC_TOKENS],
|
||||||
|
["component", tokenFiles.component, REQUIRED_COMPONENT_TOKENS],
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const [layer, file, tokens] of tokenLayers) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
for (const token of tokens) {
|
||||||
|
if (!source.includes(`${token}:`)) {
|
||||||
|
failures.push(`${layer} token is missing: ${token}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const cssSources = await Promise.all(
|
||||||
|
[...Object.values(tokenFiles), "src/presentation/styles/theme.css"].map(
|
||||||
|
async (file) => ({ file, source: await readFile(file, "utf8") }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const definitions = new Set(
|
||||||
|
cssSources.flatMap(({ source }) =>
|
||||||
|
[...source.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((match) => match[1]),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
for (const { file, source } of cssSources) {
|
||||||
|
for (const match of source.matchAll(/var\((--[a-z0-9-]+)/g)) {
|
||||||
|
if (!definitions.has(match[1])) {
|
||||||
|
failures.push(`${file} uses undefined token ${match[1]}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const semanticSource = await readFile(tokenFiles.semantic, "utf8");
|
||||||
|
const darkSource =
|
||||||
|
semanticSource.match(/:root\[data-theme="dark"\]\s*\{([\s\S]*?)\n\}/)?.[1] ??
|
||||||
|
"";
|
||||||
|
for (const token of [
|
||||||
|
"--color-surface",
|
||||||
|
"--color-surface-muted",
|
||||||
|
"--color-surface-elevated",
|
||||||
|
"--color-content",
|
||||||
|
"--color-content-muted",
|
||||||
|
"--color-content-inverse",
|
||||||
|
"--color-border",
|
||||||
|
"--color-border-strong",
|
||||||
|
"--color-action",
|
||||||
|
"--color-action-hover",
|
||||||
|
"--color-action-pressed",
|
||||||
|
"--color-danger",
|
||||||
|
"--color-focus",
|
||||||
|
"--color-disabled-content",
|
||||||
|
"--color-disabled-surface",
|
||||||
|
]) {
|
||||||
|
if (!darkSource.includes(`${token}:`)) {
|
||||||
|
failures.push(`dark theme token is missing: ${token}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const componentSource = await readFile(tokenFiles.component, "utf8");
|
||||||
|
if (!componentSource.includes("@media (forced-colors: active)")) {
|
||||||
|
failures.push("forced-colors token fallback is missing");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
|
async function listSourceFiles(directory) {
|
||||||
|
const result = [];
|
||||||
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
|
||||||
|
else if (/\.(js|jsx|mjs|ts|tsx|mts)$/.test(entry.name)) result.push(target);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sources = fixtureMode
|
||||||
|
? await listSourceFiles("tests/fixtures/design-system/forbidden")
|
||||||
|
: await listSourceFiles("src");
|
||||||
|
for (const file of sources) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
const vendorFacade =
|
||||||
|
file === "src/presentation/design-system/icons/vendors/lucide.tsx";
|
||||||
|
if (!vendorFacade && /from\s+["']lucide-react["']/.test(source)) {
|
||||||
|
failures.push(`direct icon vendor import in ${file}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
/from\s+["'](?:react-aria-components|@radix-ui\/[^"']+)["']/.test(source)
|
||||||
|
) {
|
||||||
|
failures.push(`direct headless vendor import in ${file}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!file.includes("src/presentation/design-system/") &&
|
||||||
|
/presentation\/design-system\/(?!index(?:\.js)?["'])/.test(source)
|
||||||
|
) {
|
||||||
|
failures.push(`design-system deep import in ${file}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!file.includes("src/presentation/design-system/tokens/") &&
|
||||||
|
/(?:#[0-9a-f]{3,8}\b|oklch\(|rgba?\()/i.test(source)
|
||||||
|
) {
|
||||||
|
failures.push(`raw palette value in ${file}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
file.includes("tests/fixtures/design-system/forbidden") &&
|
||||||
|
source.includes("TOOLTIP_ONLY_REQUIRED_INFORMATION")
|
||||||
|
) {
|
||||||
|
failures.push(`tooltip-only required information in ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
mode: fixtureMode ? "negative-fixture" : "source",
|
||||||
|
checkedTokenCount:
|
||||||
|
REQUIRED_PRIMITIVE_TOKENS.length +
|
||||||
|
REQUIRED_SEMANTIC_TOKENS.length +
|
||||||
|
REQUIRED_COMPONENT_TOKENS.length,
|
||||||
|
failures,
|
||||||
|
passed: failures.length === 0,
|
||||||
|
};
|
||||||
|
await mkdir("artifacts/quality", { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
fixtureMode
|
||||||
|
? "artifacts/quality/design-system-fixture.json"
|
||||||
|
: "artifacts/quality/design-system.json",
|
||||||
|
`${JSON.stringify(report, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(`Design system contract failed:\n${failures.join("\n")}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`Design system contract: ${report.checkedTokenCount} tokens and vendor boundaries PASS\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// @ts-expect-error Node 24 executes erasable TypeScript for this build-time gate.
|
||||||
|
import { DIAGNOSTIC_EVENT_REGISTRY } from "../src/contracts/diagnostics.ts";
|
||||||
|
import { TELEMETRY_REGISTRY } from "../src/contracts/telemetry.js";
|
||||||
|
|
||||||
|
const fixtureMode = process.argv.includes("--fixture");
|
||||||
|
const failures = [];
|
||||||
|
const extensions = /\.(?:js|jsx|mjs|ts|tsx|mts)$/;
|
||||||
|
|
||||||
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
|
async function filesBelow(directory) {
|
||||||
|
const result = [];
|
||||||
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
if (entry.isDirectory()) result.push(...(await filesBelow(target)));
|
||||||
|
else if (extensions.test(entry.name)) result.push(target);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
const telemetryProducerFiles =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ ({
|
||||||
|
"app.boot.failed": "src/adapters/diagnostics/bounded-diagnostics.ts",
|
||||||
|
"api.request.failed": "src/adapters/http/client.js",
|
||||||
|
"ui.render.failed": "src/application/create-application.ts",
|
||||||
|
"release.mismatch.detected": "src/application/create-application.ts",
|
||||||
|
"telemetry.delivery.dropped":
|
||||||
|
"src/adapters/telemetry/best-effort-telemetry.js",
|
||||||
|
});
|
||||||
|
const diagnosticProducerFiles =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ ({
|
||||||
|
"app.boot.failed": "src/adapters/diagnostics/bounded-diagnostics.ts",
|
||||||
|
"http.request.completed": "src/adapters/http/client.js",
|
||||||
|
"cache.operation.failed":
|
||||||
|
"src/adapters/query-cache/tanstack-query-cache.js",
|
||||||
|
"storage.operation.failed":
|
||||||
|
"src/adapters/storage/browser-storage-adapter.js",
|
||||||
|
"route.changed": "src/application/create-application.ts",
|
||||||
|
"ui.render.failed": "src/application/create-application.ts",
|
||||||
|
"release.mismatch.detected": "src/application/create-application.ts",
|
||||||
|
"telemetry.delivery.dropped": "src/bootstrap/runtime-adapters.js",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!fixtureMode) {
|
||||||
|
for (const eventName of Object.keys(TELEMETRY_REGISTRY)) {
|
||||||
|
const producer = telemetryProducerFiles[eventName];
|
||||||
|
if (!producer) {
|
||||||
|
failures.push(`telemetry event has no declared producer: ${eventName}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const source = await readFile(producer, "utf8");
|
||||||
|
if (!source.includes(`"${eventName}"`)) {
|
||||||
|
failures.push(`telemetry producer is not executable: ${eventName}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const eventId of Object.keys(DIAGNOSTIC_EVENT_REGISTRY)) {
|
||||||
|
const producer = diagnosticProducerFiles[eventId];
|
||||||
|
if (!producer) {
|
||||||
|
failures.push(`diagnostic event has no declared producer: ${eventId}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const source = await readFile(producer, "utf8");
|
||||||
|
if (!source.includes(`"${eventId}"`)) {
|
||||||
|
failures.push(`diagnostic producer is not executable: ${eventId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sources = fixtureMode
|
||||||
|
? await filesBelow("tests/fixtures/diagnostics/forbidden")
|
||||||
|
: await filesBelow("src");
|
||||||
|
const sensitiveContext =
|
||||||
|
/\b(?:authorization|cookie|access_token|refresh_token|request_body|response_body|raw_url|query_string|email|user_name)\b/i;
|
||||||
|
for (const file of sources) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
if (file.includes("contracts/telemetry.js")) continue;
|
||||||
|
if (source.includes("console.")) {
|
||||||
|
failures.push(`direct console diagnostics bypass in ${file}`);
|
||||||
|
}
|
||||||
|
const calls = source.match(
|
||||||
|
/(?:\.record\(\{|\.emit\()[\s\S]{0,700}?(?:\}\)|\}\);)/g,
|
||||||
|
) ?? [];
|
||||||
|
if (calls.some((call) => sensitiveContext.test(call))) {
|
||||||
|
failures.push(`sensitive diagnostic or telemetry context in ${file}`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
file.includes("tests/fixtures/diagnostics/forbidden") &&
|
||||||
|
source.includes("UNKNOWN_DIAGNOSTIC_EVENT")
|
||||||
|
) {
|
||||||
|
failures.push(`unknown diagnostic event in ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
mode: fixtureMode ? "negative-fixture" : "source",
|
||||||
|
telemetryEventCount: Object.keys(TELEMETRY_REGISTRY).length,
|
||||||
|
diagnosticEventCount: Object.keys(DIAGNOSTIC_EVENT_REGISTRY).length,
|
||||||
|
checkedFiles: sources.length,
|
||||||
|
failures,
|
||||||
|
passed: failures.length === 0,
|
||||||
|
};
|
||||||
|
await mkdir("artifacts/quality", { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
fixtureMode
|
||||||
|
? "artifacts/quality/diagnostics-fixture.json"
|
||||||
|
: "artifacts/quality/diagnostics.json",
|
||||||
|
`${JSON.stringify(report, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(
|
||||||
|
`Diagnostics contract failed:\n${failures.join("\n")}\n`,
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`Diagnostics contract: ${report.diagnosticEventCount} diagnostics and ${report.telemetryEventCount} telemetry producers PASS\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
// @ts-expect-error Node 24 executes erasable TypeScript for this build-time gate.
|
||||||
|
import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts";
|
||||||
|
|
||||||
|
const fixtureMode = process.argv.includes("--fixture");
|
||||||
|
const failures = [];
|
||||||
|
const sourceExtensions = /\.(?:js|jsx|mjs|ts|tsx|mts)$/;
|
||||||
|
const koreanLiteral = /[가-힣]/;
|
||||||
|
const rawFailureRender =
|
||||||
|
/(?<!\$)\{\s*(?:failure|error|response|backend)(?:\?\.|\.)[\w?.]*message\s*\}/;
|
||||||
|
|
||||||
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
|
async function listSourceFiles(directory) {
|
||||||
|
const result = [];
|
||||||
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
|
||||||
|
else if (sourceExtensions.test(entry.name)) result.push(target);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} template */
|
||||||
|
function placeholders(template) {
|
||||||
|
return [...template.matchAll(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g)]
|
||||||
|
.map((match) => match[1])
|
||||||
|
.sort();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fixtureMode) {
|
||||||
|
const canonicalKeys = Object.keys(KO_MESSAGES).sort();
|
||||||
|
for (const [locale, catalog] of Object.entries(MESSAGE_CATALOGS)) {
|
||||||
|
const readableCatalog =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ (catalog);
|
||||||
|
const canonicalCatalog =
|
||||||
|
/** @type {Readonly<Record<string, string>>} */ (KO_MESSAGES);
|
||||||
|
const keys = Object.keys(catalog).sort();
|
||||||
|
if (JSON.stringify(keys) !== JSON.stringify(canonicalKeys)) {
|
||||||
|
failures.push(`${locale} catalog keys do not match ko-KR`);
|
||||||
|
}
|
||||||
|
for (const key of canonicalKeys) {
|
||||||
|
if (
|
||||||
|
JSON.stringify(placeholders(readableCatalog[key] ?? "")) !==
|
||||||
|
JSON.stringify(placeholders(canonicalCatalog[key] ?? ""))
|
||||||
|
) {
|
||||||
|
failures.push(`${locale}:${key} interpolation parameters do not match`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(EN_MESSAGES).length !== canonicalKeys.length) {
|
||||||
|
failures.push("en-US catalog key count does not match ko-KR");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const commonDirectories = [
|
||||||
|
"src/presentation/boundaries",
|
||||||
|
"src/presentation/components",
|
||||||
|
"src/presentation/design-system",
|
||||||
|
"src/presentation/forms",
|
||||||
|
"src/presentation/layouts",
|
||||||
|
"src/presentation/routes",
|
||||||
|
"src/presentation/templates",
|
||||||
|
];
|
||||||
|
const sources = fixtureMode
|
||||||
|
? await listSourceFiles("tests/fixtures/i18n/forbidden")
|
||||||
|
: (
|
||||||
|
await Promise.all(commonDirectories.map((directory) => listSourceFiles(directory)))
|
||||||
|
).flat();
|
||||||
|
|
||||||
|
for (const file of sources) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
if (koreanLiteral.test(source)) {
|
||||||
|
failures.push(`hardcoded common user-facing locale literal in ${file}`);
|
||||||
|
}
|
||||||
|
if (rawFailureRender.test(source)) {
|
||||||
|
failures.push(`raw backend/error message rendered in ${file}`);
|
||||||
|
}
|
||||||
|
if (source.includes("dangerouslySetInnerHTML")) {
|
||||||
|
failures.push(`untrusted HTML interpolation boundary in ${file}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
mode: fixtureMode ? "negative-fixture" : "source",
|
||||||
|
localeCount: Object.keys(MESSAGE_CATALOGS).length + 1,
|
||||||
|
messageKeyCount: Object.keys(KO_MESSAGES).length,
|
||||||
|
checkedFiles: sources.length,
|
||||||
|
failures,
|
||||||
|
passed: failures.length === 0,
|
||||||
|
};
|
||||||
|
await mkdir("artifacts/quality", { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
fixtureMode
|
||||||
|
? "artifacts/quality/i18n-fixture.json"
|
||||||
|
: "artifacts/quality/i18n.json",
|
||||||
|
`${JSON.stringify(report, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(`I18n contract failed:\n${failures.join("\n")}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`I18n contract: ${report.messageKeyCount} keys across ${report.localeCount} locales PASS\n`,
|
||||||
|
);
|
||||||
+243
-56
@@ -1,28 +1,65 @@
|
|||||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
import {
|
||||||
|
access,
|
||||||
|
mkdir,
|
||||||
|
readFile,
|
||||||
|
readdir,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { pathToFileURL } from "node:url";
|
import { pathToFileURL } from "node:url";
|
||||||
|
|
||||||
/** @param {string} name @param {string} fallback */
|
import {
|
||||||
|
canonicalizeRegistryValue,
|
||||||
|
diffRegistrySnapshots,
|
||||||
|
registrySnapshotDigest,
|
||||||
|
validateBreakingEvidence,
|
||||||
|
verifyRegistryBaselineApproval,
|
||||||
|
} from "./lib/registry-compatibility.mjs";
|
||||||
|
|
||||||
|
/** @param {string} name @param {string | undefined} fallback */
|
||||||
function argumentValue(name, fallback) {
|
function argumentValue(name, fallback) {
|
||||||
const index = process.argv.indexOf(name);
|
const index = process.argv.indexOf(name);
|
||||||
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
|
return index >= 0 && process.argv[index + 1]
|
||||||
|
? process.argv[index + 1]
|
||||||
|
: fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
const governancePath = argumentValue(
|
const defaultGovernancePath = "config/contracts/registry-governance.json";
|
||||||
"--governance",
|
const governancePath =
|
||||||
"config/contracts/registry-governance.json",
|
/** @type {string} */ (
|
||||||
|
argumentValue("--governance", defaultGovernancePath)
|
||||||
|
);
|
||||||
|
const artifactPath =
|
||||||
|
/** @type {string} */ (
|
||||||
|
argumentValue("--artifact", "artifacts/quality/registries.json")
|
||||||
|
);
|
||||||
|
const usesRepositoryBaseline =
|
||||||
|
governancePath === defaultGovernancePath &&
|
||||||
|
!process.argv.includes("--no-baseline");
|
||||||
|
const baselinePath = argumentValue(
|
||||||
|
"--baseline",
|
||||||
|
usesRepositoryBaseline
|
||||||
|
? "config/contracts/registry-baseline.json"
|
||||||
|
: undefined,
|
||||||
);
|
);
|
||||||
const artifactPath = argumentValue(
|
const approvalPath = argumentValue(
|
||||||
"--artifact",
|
"--approval",
|
||||||
"artifacts/quality/registries.json",
|
usesRepositoryBaseline
|
||||||
|
? "config/contracts/registry-baseline.approval.json"
|
||||||
|
: undefined,
|
||||||
);
|
);
|
||||||
const governance = JSON.parse(
|
const evidencePath = argumentValue(
|
||||||
await readFile(governancePath, "utf8"),
|
"--compatibility-evidence",
|
||||||
|
usesRepositoryBaseline
|
||||||
|
? "config/contracts/registry-change-evidence.json"
|
||||||
|
: undefined,
|
||||||
);
|
);
|
||||||
|
const governance = JSON.parse(await readFile(governancePath, "utf8"));
|
||||||
const failures = [];
|
const failures = [];
|
||||||
const owners = new Map();
|
const owners = new Map();
|
||||||
const snapshots = [];
|
const snapshots = [];
|
||||||
const rowsByRegistry = new Map();
|
const rowsByRegistry = new Map();
|
||||||
|
const sourcesByRegistry = new Map();
|
||||||
const registryExtensions = [".js", ".jsx", ".mjs", ".ts", ".tsx", ".mts"];
|
const registryExtensions = [".js", ".jsx", ".mjs", ".ts", ".tsx", ".mts"];
|
||||||
|
|
||||||
/** @param {string} declaredPath */
|
/** @param {string} declaredPath */
|
||||||
@@ -38,7 +75,7 @@ async function resolveRegistrySource(declaredPath) {
|
|||||||
await access(candidate);
|
await access(candidate);
|
||||||
candidates.push(candidate);
|
candidates.push(candidate);
|
||||||
} catch {
|
} catch {
|
||||||
// A migration may legitimately replace the declared extension.
|
// A TypeScript migration may replace the declared extension.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (candidates.length > 1) {
|
if (candidates.length > 1) {
|
||||||
@@ -50,6 +87,44 @@ async function resolveRegistrySource(declaredPath) {
|
|||||||
return candidates[0] ?? null;
|
return candidates[0] ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @param {unknown} value */
|
||||||
|
function runtimeType(value) {
|
||||||
|
if (value === null) return "null";
|
||||||
|
if (Array.isArray(value)) return "array";
|
||||||
|
if (Number.isInteger(value)) return "integer";
|
||||||
|
return typeof value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {unknown} value @param {string} declaration */
|
||||||
|
function matchesDeclaredType(value, declaration) {
|
||||||
|
const actual = runtimeType(value);
|
||||||
|
return declaration
|
||||||
|
.split("|")
|
||||||
|
.some(
|
||||||
|
(candidate) =>
|
||||||
|
candidate === actual ||
|
||||||
|
(candidate === "number" && actual === "integer"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
|
async function filesBelow(directory) {
|
||||||
|
try {
|
||||||
|
const entries = await readdir(directory, { withFileTypes: true });
|
||||||
|
const groups = await Promise.all(
|
||||||
|
entries.map((entry) => {
|
||||||
|
const target = path.join(directory, entry.name);
|
||||||
|
return entry.isDirectory() ? filesBelow(target) : [target];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return groups.flat().filter((file) =>
|
||||||
|
/\.(?:js|jsx|mjs|ts|tsx|mts)$/.test(file),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for (const specification of governance.registries) {
|
for (const specification of governance.registries) {
|
||||||
if (owners.has(specification.registryId)) {
|
if (owners.has(specification.registryId)) {
|
||||||
failures.push(`duplicate owner for ${specification.registryId}`);
|
failures.push(`duplicate owner for ${specification.registryId}`);
|
||||||
@@ -74,6 +149,10 @@ for (const specification of governance.registries) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rowsByRegistry.set(specification.registryId, rows);
|
rowsByRegistry.set(specification.registryId, rows);
|
||||||
|
sourcesByRegistry.set(
|
||||||
|
specification.registryId,
|
||||||
|
sourcePath ?? specification.path,
|
||||||
|
);
|
||||||
|
|
||||||
for (const [rowName, row] of Object.entries(rows)) {
|
for (const [rowName, row] of Object.entries(rows)) {
|
||||||
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
if (!row || typeof row !== "object" || Array.isArray(row)) {
|
||||||
@@ -85,6 +164,26 @@ for (const specification of governance.registries) {
|
|||||||
failures.push(`${specification.registryId}.${rowName} missing ${field}`);
|
failures.push(`${specification.registryId}.${rowName} missing ${field}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for (const [field, declaredType] of Object.entries(
|
||||||
|
specification.fieldTypes ?? {},
|
||||||
|
)) {
|
||||||
|
if (
|
||||||
|
field in row &&
|
||||||
|
!matchesDeclaredType(row[field], String(declaredType))
|
||||||
|
) {
|
||||||
|
failures.push(
|
||||||
|
`${specification.registryId}.${rowName}.${field} expected ${declaredType}, received ${runtimeType(row[field])}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
specification.keyField &&
|
||||||
|
row[specification.keyField] !== rowName
|
||||||
|
) {
|
||||||
|
failures.push(
|
||||||
|
`${specification.registryId}.${rowName}.${specification.keyField} must match its registry key`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const field of specification.uniqueFields ?? []) {
|
for (const field of specification.uniqueFields ?? []) {
|
||||||
@@ -93,12 +192,13 @@ for (const specification of governance.registries) {
|
|||||||
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
|
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
|
||||||
const value = row[field];
|
const value = row[field];
|
||||||
if (value === undefined) continue;
|
if (value === undefined) continue;
|
||||||
if (values.has(value)) {
|
const identity = JSON.stringify(canonicalizeRegistryValue(value));
|
||||||
|
if (values.has(identity)) {
|
||||||
failures.push(
|
failures.push(
|
||||||
`${specification.registryId}.${rowName} duplicates ${field}=${String(value)} from ${values.get(value)}`,
|
`${specification.registryId}.${rowName} duplicates ${field}=${String(value)} from ${values.get(identity)}`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
values.set(value, rowName);
|
values.set(identity, rowName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -121,12 +221,22 @@ for (const specification of governance.registries) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const contract = Object.freeze({
|
||||||
|
requiredFields: specification.requiredFields,
|
||||||
|
fieldTypes: specification.fieldTypes ?? {},
|
||||||
|
uniqueFields: specification.uniqueFields ?? [],
|
||||||
|
allowedValues: specification.allowedValues ?? {},
|
||||||
|
references: specification.references ?? [],
|
||||||
|
keyField: specification.keyField ?? null,
|
||||||
|
breakingFields: specification.breakingFields ?? [],
|
||||||
|
});
|
||||||
snapshots.push({
|
snapshots.push({
|
||||||
registryId: specification.registryId,
|
registryId: specification.registryId,
|
||||||
owner: specification.owner,
|
owner: specification.owner,
|
||||||
source: sourcePath ?? specification.path,
|
source: sourcePath ?? specification.path,
|
||||||
rowCount: Object.keys(rows).length,
|
rowCount: Object.keys(rows).length,
|
||||||
rows,
|
contract,
|
||||||
|
rows: canonicalizeRegistryValue(rows),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,18 +255,74 @@ for (const specification of governance.registries) {
|
|||||||
Object.values(targetRows)
|
Object.values(targetRows)
|
||||||
.filter((row) => row && typeof row === "object" && !Array.isArray(row))
|
.filter((row) => row && typeof row === "object" && !Array.isArray(row))
|
||||||
.map((row) => row[reference.targetField])
|
.map((row) => row[reference.targetField])
|
||||||
.filter((value) => value !== undefined),
|
.filter((value) => value !== undefined && value !== null),
|
||||||
);
|
);
|
||||||
for (const [rowName, row] of Object.entries(rows)) {
|
for (const [rowName, row] of Object.entries(rows)) {
|
||||||
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
|
if (!row || typeof row !== "object" || Array.isArray(row)) continue;
|
||||||
const value = row[reference.field];
|
const value = row[reference.field];
|
||||||
if (value !== undefined && !targetValues.has(value)) {
|
if (
|
||||||
|
value !== undefined &&
|
||||||
|
value !== null &&
|
||||||
|
!targetValues.has(value)
|
||||||
|
) {
|
||||||
failures.push(
|
failures.push(
|
||||||
`${specification.registryId}.${rowName}.${reference.field} references unknown ${reference.registryId}.${reference.targetField}=${String(value)}`,
|
`${specification.registryId}.${rowName}.${reference.field} references unknown ${reference.registryId}.${reference.targetField}=${String(value)}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
for (const consumer of specification.consumers ?? []) {
|
||||||
|
try {
|
||||||
|
const source = await readFile(consumer.path, "utf8");
|
||||||
|
if (!source.includes(consumer.token)) {
|
||||||
|
failures.push(
|
||||||
|
`${specification.registryId} consumer ${consumer.path} is missing ${consumer.token}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
failures.push(
|
||||||
|
`${specification.registryId} consumer source is missing: ${consumer.path}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (specification.consumerIdentityField) {
|
||||||
|
const consumerFiles = (
|
||||||
|
await Promise.all(
|
||||||
|
(specification.consumerDirectories ?? []).map(filesBelow),
|
||||||
|
)
|
||||||
|
).flat();
|
||||||
|
const sourcePath = sourcesByRegistry.get(specification.registryId);
|
||||||
|
const consumerText = (
|
||||||
|
await Promise.all(
|
||||||
|
consumerFiles
|
||||||
|
.filter((file) => file !== sourcePath)
|
||||||
|
.map((file) => readFile(file, "utf8")),
|
||||||
|
)
|
||||||
|
).join("\n");
|
||||||
|
const exemptions = new Set(specification.orphanExemptRows ?? []);
|
||||||
|
for (const [rowName, row] of Object.entries(rows)) {
|
||||||
|
if (
|
||||||
|
!row ||
|
||||||
|
typeof row !== "object" ||
|
||||||
|
Array.isArray(row) ||
|
||||||
|
exemptions.has(rowName)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const identity = row[specification.consumerIdentityField];
|
||||||
|
if (
|
||||||
|
(typeof identity !== "string" &&
|
||||||
|
typeof identity !== "number") ||
|
||||||
|
!consumerText.includes(String(identity))
|
||||||
|
) {
|
||||||
|
failures.push(
|
||||||
|
`${specification.registryId}.${rowName} has no executable consumer for ${specification.consumerIdentityField}=${String(identity)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const sourceFiles = governance.sourceDirectories ?? [
|
const sourceFiles = governance.sourceDirectories ?? [
|
||||||
@@ -166,59 +332,80 @@ const sourceFiles = governance.sourceDirectories ?? [
|
|||||||
];
|
];
|
||||||
const adHocPatterns = [
|
const adHocPatterns = [
|
||||||
{ name: "direct fetch", expression: /\bfetch\s*\(/ },
|
{ name: "direct fetch", expression: /\bfetch\s*\(/ },
|
||||||
{ name: "direct localStorage", expression: /\blocalStorage\.(?:get|set|remove)Item/ },
|
{
|
||||||
|
name: "direct localStorage",
|
||||||
|
expression: /\blocalStorage\.(?:get|set|remove)Item/,
|
||||||
|
},
|
||||||
{ name: "direct import.meta.env", expression: /\bimport\.meta\.env\./ },
|
{ name: "direct import.meta.env", expression: /\bimport\.meta\.env\./ },
|
||||||
{ name: "raw API path", expression: /["']\/api\// },
|
{ name: "raw API path", expression: /["']\/api\// },
|
||||||
];
|
];
|
||||||
|
|
||||||
/** @param {string} directory */
|
for (const sourceDirectory of sourceFiles) {
|
||||||
async function scanDirectory(directory) {
|
for (const file of await filesBelow(sourceDirectory)) {
|
||||||
try {
|
const content = await readFile(file, "utf8");
|
||||||
await access(directory);
|
|
||||||
} catch {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const entries = await import("node:fs/promises").then(({ readdir }) =>
|
|
||||||
readdir(directory, { withFileTypes: true }),
|
|
||||||
);
|
|
||||||
for (const entry of entries) {
|
|
||||||
const target = path.join(directory, entry.name);
|
|
||||||
if (entry.isDirectory()) {
|
|
||||||
await scanDirectory(target);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if (!/\.(js|jsx|mjs|ts|tsx|mts)$/.test(entry.name)) continue;
|
|
||||||
const content = await readFile(target, "utf8");
|
|
||||||
for (const pattern of adHocPatterns) {
|
for (const pattern of adHocPatterns) {
|
||||||
if (pattern.expression.test(content)) {
|
if (pattern.expression.test(content)) {
|
||||||
failures.push(`ad-hoc ${pattern.name} in ${target}`);
|
failures.push(`ad-hoc ${pattern.name} in ${file}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const sourceDirectory of sourceFiles) {
|
const currentSnapshot =
|
||||||
await scanDirectory(sourceDirectory);
|
/** @type {Readonly<Record<string, unknown>>} */ (
|
||||||
|
canonicalizeRegistryValue({
|
||||||
|
schemaVersion: 2,
|
||||||
|
registries: snapshots,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
let baselineDigest = null;
|
||||||
|
let currentDigest = registrySnapshotDigest(currentSnapshot);
|
||||||
|
let compatibility =
|
||||||
|
/** @type {{impact: string, changes: readonly Record<string, unknown>[]}} */ ({
|
||||||
|
impact: "not-evaluated",
|
||||||
|
changes: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (baselinePath && approvalPath && evidencePath) {
|
||||||
|
try {
|
||||||
|
const baseline = JSON.parse(await readFile(baselinePath, "utf8"));
|
||||||
|
const approval = JSON.parse(await readFile(approvalPath, "utf8"));
|
||||||
|
const approvalResult = verifyRegistryBaselineApproval(baseline, approval);
|
||||||
|
baselineDigest = approvalResult.actualDigest;
|
||||||
|
if (!approvalResult.passed) {
|
||||||
|
failures.push(
|
||||||
|
`registry baseline approval digest mismatch: approved=${approvalResult.approvedDigest} actual=${approvalResult.actualDigest}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
compatibility = diffRegistrySnapshots(baseline, currentSnapshot);
|
||||||
|
const evidence = JSON.parse(await readFile(evidencePath, "utf8"));
|
||||||
|
const evidenceResult = validateBreakingEvidence(compatibility, evidence);
|
||||||
|
failures.push(...evidenceResult.failures);
|
||||||
|
} catch (error) {
|
||||||
|
failures.push(
|
||||||
|
`registry compatibility evidence unavailable: ${
|
||||||
|
error instanceof Error ? error.name : "unknown"
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await mkdir("artifacts/quality", { recursive: true });
|
const report = {
|
||||||
await writeFile(
|
schemaVersion: 2,
|
||||||
artifactPath,
|
generatedAt: new Date().toISOString(),
|
||||||
`${JSON.stringify(
|
baselineDigest,
|
||||||
{
|
currentDigest,
|
||||||
schemaVersion: 1,
|
compatibility,
|
||||||
generatedAt: new Date().toISOString(),
|
failures,
|
||||||
compatibilityImpact: governance.compatibilityImpact.current,
|
registries: snapshots,
|
||||||
failures,
|
};
|
||||||
registries: snapshots,
|
await mkdir(path.dirname(artifactPath), { recursive: true });
|
||||||
},
|
await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||||
null,
|
|
||||||
2,
|
|
||||||
)}\n`,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (failures.length > 0) {
|
if (failures.length > 0) {
|
||||||
process.stderr.write(`Registry governance failed:\n${failures.join("\n")}\n`);
|
process.stderr.write(`Registry governance failed:\n${failures.join("\n")}\n`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
process.stdout.write(`Registry governance: ${snapshots.length} registries PASS\n`);
|
process.stdout.write(
|
||||||
|
`Registry governance: ${snapshots.length} registries PASS; compatibility=${compatibility.impact}\n`,
|
||||||
|
);
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||||
|
|
||||||
|
import {
|
||||||
|
diffRegistrySnapshots,
|
||||||
|
validateBreakingEvidence,
|
||||||
|
verifyRegistryBaselineApproval,
|
||||||
|
} from "./lib/registry-compatibility.mjs";
|
||||||
|
|
||||||
|
const fixtures = JSON.parse(
|
||||||
|
await readFile(
|
||||||
|
"tests/fixtures/registry/compatibility/semantic-diff.json",
|
||||||
|
"utf8",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const results = [];
|
||||||
|
for (const fixture of fixtures.cases) {
|
||||||
|
const actual = diffRegistrySnapshots(fixture.before, fixture.after);
|
||||||
|
results.push({
|
||||||
|
id: fixture.id,
|
||||||
|
expected: fixture.expected,
|
||||||
|
actual: actual.impact,
|
||||||
|
passed: actual.impact === fixture.expected,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const breaking = diffRegistrySnapshots(
|
||||||
|
fixtures.breakingEvidence.before,
|
||||||
|
fixtures.breakingEvidence.after,
|
||||||
|
);
|
||||||
|
const missingEvidence = validateBreakingEvidence(breaking, {
|
||||||
|
schemaVersion: 1,
|
||||||
|
changes: [],
|
||||||
|
});
|
||||||
|
results.push({
|
||||||
|
id: "breaking-evidence-required",
|
||||||
|
expected: false,
|
||||||
|
actual: missingEvidence.passed,
|
||||||
|
passed: !missingEvidence.passed,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tamperedApproval = verifyRegistryBaselineApproval(
|
||||||
|
fixtures.tamperedApproval.snapshot,
|
||||||
|
fixtures.tamperedApproval.approval,
|
||||||
|
);
|
||||||
|
results.push({
|
||||||
|
id: "tampered-baseline-digest",
|
||||||
|
expected: false,
|
||||||
|
actual: tamperedApproval.passed,
|
||||||
|
passed: !tamperedApproval.passed,
|
||||||
|
});
|
||||||
|
|
||||||
|
await mkdir("artifacts/quality", { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
"artifacts/quality/registry-compatibility-fixtures.json",
|
||||||
|
`${JSON.stringify({ schemaVersion: 1, results }, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
if (results.some((result) => !result.passed)) {
|
||||||
|
process.stderr.write("Registry compatibility fixture failed.\n");
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`Registry compatibility fixtures: ${results.length} PASS\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
/** @param {string} name @param {string} fallback */
|
||||||
|
function argumentValue(name, fallback) {
|
||||||
|
const index = process.argv.indexOf(name);
|
||||||
|
return index >= 0 && process.argv[index + 1]
|
||||||
|
? process.argv[index + 1]
|
||||||
|
: fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const policyPath = argumentValue(
|
||||||
|
"--policy",
|
||||||
|
"config/testing/risk-coverage.json",
|
||||||
|
);
|
||||||
|
const summaryPath = argumentValue(
|
||||||
|
"--summary",
|
||||||
|
"artifacts/tests/coverage/coverage-summary.json",
|
||||||
|
);
|
||||||
|
const artifactPath = argumentValue(
|
||||||
|
"--artifact",
|
||||||
|
"artifacts/quality/risk-coverage.json",
|
||||||
|
);
|
||||||
|
const policy = JSON.parse(await readFile(policyPath, "utf8"));
|
||||||
|
const summary = JSON.parse(await readFile(summaryPath, "utf8"));
|
||||||
|
const failures = [];
|
||||||
|
/** @type {Array<{
|
||||||
|
* scope: string,
|
||||||
|
* metric: string,
|
||||||
|
* threshold: number,
|
||||||
|
* received: number | undefined,
|
||||||
|
* passed: boolean
|
||||||
|
* }>} */
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} scope
|
||||||
|
* @param {Record<string, {pct: number}>} actual
|
||||||
|
* @param {Record<string, number>} minimum
|
||||||
|
*/
|
||||||
|
function evaluate(scope, actual, minimum) {
|
||||||
|
for (const [metric, threshold] of Object.entries(minimum)) {
|
||||||
|
const received = actual?.[metric]?.pct;
|
||||||
|
const passed =
|
||||||
|
typeof received === "number" &&
|
||||||
|
Number.isFinite(received) &&
|
||||||
|
received >= threshold;
|
||||||
|
results.push({ scope, metric, threshold, received, passed });
|
||||||
|
if (!passed) {
|
||||||
|
failures.push(
|
||||||
|
`${scope}.${metric} expected >= ${threshold}, received ${String(received)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
evaluate("total", summary.total, policy.summary);
|
||||||
|
for (const modulePolicy of policy.criticalModules) {
|
||||||
|
const key = Object.keys(summary).find(
|
||||||
|
(candidate) =>
|
||||||
|
candidate !== "total" &&
|
||||||
|
candidate.replaceAll("\\", "/").endsWith(`/${modulePolicy.path}`),
|
||||||
|
);
|
||||||
|
if (!key) {
|
||||||
|
failures.push(`critical module missing from coverage: ${modulePolicy.path}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
evaluate(modulePolicy.path, summary[key], modulePolicy.minimum);
|
||||||
|
}
|
||||||
|
|
||||||
|
const artifact = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
policy: policyPath,
|
||||||
|
summary: summaryPath,
|
||||||
|
status: failures.length === 0 ? "PASS" : "FAIL",
|
||||||
|
results,
|
||||||
|
failures,
|
||||||
|
};
|
||||||
|
await mkdir(path.dirname(artifactPath), { recursive: true });
|
||||||
|
await writeFile(artifactPath, `${JSON.stringify(artifact, null, 2)}\n`);
|
||||||
|
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(`Risk coverage failed:\n- ${failures.join("\n- ")}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`Risk coverage: PASS (${results.length} scoped thresholds)\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
/** @param {string} name @param {string} fallback */
|
||||||
|
function argumentValue(name, fallback) {
|
||||||
|
const index = process.argv.indexOf(name);
|
||||||
|
return index >= 0 && process.argv[index + 1]
|
||||||
|
? process.argv[index + 1]
|
||||||
|
: fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceRoot = argumentValue("--source-root", "tests");
|
||||||
|
const artifactPath = argumentValue(
|
||||||
|
"--artifact",
|
||||||
|
"artifacts/quality/test-evidence.json",
|
||||||
|
);
|
||||||
|
const fixtureMode = sourceRoot !== "tests";
|
||||||
|
const failures = [];
|
||||||
|
const facts = {
|
||||||
|
scannedFiles: 0,
|
||||||
|
visualBaselines: 0,
|
||||||
|
sharedScenarios: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @param {string} target @returns {Promise<string[]>} */
|
||||||
|
async function filesBelow(target) {
|
||||||
|
try {
|
||||||
|
const metadata = await stat(target);
|
||||||
|
if (metadata.isFile()) return [target];
|
||||||
|
const entries = await readdir(target, { withFileTypes: true });
|
||||||
|
const groups = await Promise.all(
|
||||||
|
entries.map((entry) => filesBelow(path.join(target, entry.name))),
|
||||||
|
);
|
||||||
|
return groups.flat();
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceFiles = (await filesBelow(sourceRoot)).filter(
|
||||||
|
(file) => fixtureMode || !file.split(path.sep).includes("fixtures"),
|
||||||
|
);
|
||||||
|
for (const file of sourceFiles) {
|
||||||
|
if (!/\.(?:js|jsx|mjs|ts|tsx|fixture|txt)$/.test(file)) continue;
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
facts.scannedFiles += 1;
|
||||||
|
const skipPattern =
|
||||||
|
/\b(?:test|it|describe)(?:\.describe)?\.(?:skip|fixme)\s*\(/g;
|
||||||
|
if (skipPattern.test(source)) {
|
||||||
|
const quarantine =
|
||||||
|
/quarantine\(owner=[^)]+,\s*defect=[^)]+,\s*expires=\d{4}-\d{2}-\d{2}\)/;
|
||||||
|
if (!quarantine.test(source)) {
|
||||||
|
failures.push(`${file}: skip/fixme lacks owned expiring quarantine`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const wholeUiMask =
|
||||||
|
/\bmask\s*:\s*\[[\s\S]{0,240}(?:locator|getByRole)\s*\(\s*["'](?:html|body|main|application|document)["']/i;
|
||||||
|
if (wholeUiMask.test(source)) {
|
||||||
|
failures.push(`${file}: screenshot mask may not cover the whole UI`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fixtureMode) {
|
||||||
|
const e2eConfig = await readFile("playwright.config.js", "utf8");
|
||||||
|
for (const token of [
|
||||||
|
"pnpm build",
|
||||||
|
"pnpm preview",
|
||||||
|
"reuseExistingServer: false",
|
||||||
|
'"junit"',
|
||||||
|
'trace: "retain-on-failure"',
|
||||||
|
'"chromium-compact"',
|
||||||
|
'"firefox"',
|
||||||
|
'"webkit"',
|
||||||
|
]) {
|
||||||
|
if (!e2eConfig.includes(token)) {
|
||||||
|
failures.push(`playwright.config.js missing release evidence token ${token}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const e2eFiles = (await filesBelow("tests/e2e")).filter((file) =>
|
||||||
|
/\.spec\.(?:js|ts)$/.test(file),
|
||||||
|
);
|
||||||
|
for (const file of e2eFiles) {
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
if (!source.includes("support/browser/strict-browser-test")) {
|
||||||
|
failures.push(`${file}: bypasses strict browser fixture`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const scenarioCatalog = await readFile(
|
||||||
|
"tests/mocks/scenarios/catalog.ts",
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
const scenarioIdBlock =
|
||||||
|
scenarioCatalog.match(
|
||||||
|
/HTTP_SCENARIO_IDS\s*=\s*Object\.freeze\(\[([\s\S]*?)\]\s*as const\)/,
|
||||||
|
)?.[1] ?? "";
|
||||||
|
facts.sharedScenarios = (scenarioIdBlock.match(/"[^"]+"/g) ?? []).length;
|
||||||
|
if (facts.sharedScenarios < 19) {
|
||||||
|
failures.push("shared MSW catalog must retain all 19 failure scenarios");
|
||||||
|
}
|
||||||
|
const handler = await readFile(
|
||||||
|
"tests/mocks/handlers/reference-resources.ts",
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
!handler.includes("assertOperationScenario") ||
|
||||||
|
!handler.includes("../scenarios/catalog.js")
|
||||||
|
) {
|
||||||
|
failures.push("MSW handler bypasses shared scenario catalog");
|
||||||
|
}
|
||||||
|
|
||||||
|
const baselineFiles = (await filesBelow("tests/visual/__snapshots__")).filter(
|
||||||
|
(file) => file.endsWith(".png"),
|
||||||
|
);
|
||||||
|
facts.visualBaselines = baselineFiles.length;
|
||||||
|
if (facts.visualBaselines < 4) {
|
||||||
|
failures.push("visual baseline requires at least four risk surfaces");
|
||||||
|
}
|
||||||
|
for (const required of [
|
||||||
|
"playwright.storybook.config.js",
|
||||||
|
"playwright.visual.config.js",
|
||||||
|
"tests/storybook/workshop.spec.ts",
|
||||||
|
"artifacts/tests/storybook/results.xml",
|
||||||
|
"artifacts/tests/visual/results.xml",
|
||||||
|
]) {
|
||||||
|
if ((await filesBelow(required)).length === 0) {
|
||||||
|
failures.push(`test evidence missing ${required}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const requiredBuiltFiles = [
|
||||||
|
"dist/index.html",
|
||||||
|
"dist/config.json",
|
||||||
|
"dist/release-manifest.json",
|
||||||
|
"dist/runtime-config.schema.json",
|
||||||
|
"dist/.vite/manifest.json",
|
||||||
|
];
|
||||||
|
for (const required of requiredBuiltFiles) {
|
||||||
|
if ((await filesBelow(required)).length === 0) {
|
||||||
|
failures.push(`built-dist contract missing ${required}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const sourceMaps = (await filesBelow("dist")).filter((file) =>
|
||||||
|
file.endsWith(".map"),
|
||||||
|
);
|
||||||
|
if (sourceMaps.length > 0) {
|
||||||
|
failures.push(`production dist contains source maps: ${sourceMaps.join(", ")}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = {
|
||||||
|
schemaVersion: 1,
|
||||||
|
sourceRoot,
|
||||||
|
status: failures.length === 0 ? "PASS" : "FAIL",
|
||||||
|
facts,
|
||||||
|
failures,
|
||||||
|
};
|
||||||
|
await mkdir(path.dirname(artifactPath), { recursive: true });
|
||||||
|
await writeFile(artifactPath, `${JSON.stringify(report, null, 2)}\n`);
|
||||||
|
if (failures.length > 0) {
|
||||||
|
process.stderr.write(`Test evidence failed:\n- ${failures.join("\n- ")}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
process.stdout.write(
|
||||||
|
`Test evidence: PASS (${facts.scannedFiles} files, ${facts.visualBaselines} baselines, ${facts.sharedScenarios} scenarios)\n`,
|
||||||
|
);
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
|
||||||
|
export const COMPATIBILITY_IMPACTS = Object.freeze([
|
||||||
|
"none",
|
||||||
|
"additive",
|
||||||
|
"behavior-change",
|
||||||
|
"breaking",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const impactRank = new Map(
|
||||||
|
COMPATIBILITY_IMPACTS.map((impact, index) => [impact, index]),
|
||||||
|
);
|
||||||
|
|
||||||
|
/** @param {unknown} value @returns {unknown} */
|
||||||
|
export function canonicalizeRegistryValue(value) {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
const projected =
|
||||||
|
/** @type {unknown[]} */ (value.map(canonicalizeRegistryValue));
|
||||||
|
return projected.every(
|
||||||
|
(item) =>
|
||||||
|
item === null ||
|
||||||
|
["string", "number", "boolean"].includes(typeof item),
|
||||||
|
)
|
||||||
|
? projected.sort((left, right) =>
|
||||||
|
JSON.stringify(left).localeCompare(JSON.stringify(right)),
|
||||||
|
)
|
||||||
|
: projected;
|
||||||
|
}
|
||||||
|
if (value && typeof value === "object") {
|
||||||
|
return Object.fromEntries(
|
||||||
|
Object.entries(value)
|
||||||
|
.sort(([left], [right]) => left.localeCompare(right))
|
||||||
|
.map(([key, item]) => [key, canonicalizeRegistryValue(item)]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {unknown} value @returns {string} */
|
||||||
|
export function canonicalRegistryJson(value) {
|
||||||
|
return JSON.stringify(canonicalizeRegistryValue(value)) ?? "undefined";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {unknown} snapshot */
|
||||||
|
export function registrySnapshotDigest(snapshot) {
|
||||||
|
return createHash("sha256")
|
||||||
|
.update(canonicalRegistryJson(snapshot))
|
||||||
|
.digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} current @param {string} candidate */
|
||||||
|
function strongestImpact(current, candidate) {
|
||||||
|
return (impactRank.get(candidate) ?? 0) > (impactRank.get(current) ?? 0)
|
||||||
|
? candidate
|
||||||
|
: current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {unknown} value */
|
||||||
|
function valueType(value) {
|
||||||
|
if (value === null) return "null";
|
||||||
|
if (Array.isArray(value)) return "array";
|
||||||
|
return typeof value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} registryId
|
||||||
|
* @param {string} rowName
|
||||||
|
* @param {string} field
|
||||||
|
* @param {string} kind
|
||||||
|
*/
|
||||||
|
function changeId(registryId, rowName, field, kind) {
|
||||||
|
return `${registryId}:${rowName}:${field}:${kind}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates a semantic diff. Object key and primitive-array ordering is
|
||||||
|
* canonicalized before comparison and therefore cannot create a false change.
|
||||||
|
*
|
||||||
|
* @param {Readonly<Record<string, unknown>>} before
|
||||||
|
* @param {Readonly<Record<string, unknown>>} after
|
||||||
|
*/
|
||||||
|
export function diffRegistrySnapshots(before, after) {
|
||||||
|
const changes = /** @type {Array<Record<string, unknown>>} */ ([]);
|
||||||
|
let impact = "none";
|
||||||
|
const beforeRegistries =
|
||||||
|
/** @type {Map<string, Record<string, unknown>>} */ (new Map(
|
||||||
|
/** @type {Array<Record<string, unknown>>} */ (before.registries ?? []).map(
|
||||||
|
(registry) => [String(registry.registryId), registry],
|
||||||
|
),
|
||||||
|
));
|
||||||
|
const afterRegistries =
|
||||||
|
/** @type {Map<string, Record<string, unknown>>} */ (new Map(
|
||||||
|
/** @type {Array<Record<string, unknown>>} */ (after.registries ?? []).map(
|
||||||
|
(registry) => [String(registry.registryId), registry],
|
||||||
|
),
|
||||||
|
));
|
||||||
|
const registryIds = new Set([
|
||||||
|
...beforeRegistries.keys(),
|
||||||
|
...afterRegistries.keys(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
for (const registryId of [...registryIds].sort()) {
|
||||||
|
const previous = beforeRegistries.get(registryId);
|
||||||
|
const current = afterRegistries.get(registryId);
|
||||||
|
if (!previous || !current) {
|
||||||
|
const changeImpact = previous ? "breaking" : "additive";
|
||||||
|
impact = strongestImpact(impact, changeImpact);
|
||||||
|
changes.push({
|
||||||
|
changeId: changeId(registryId, "*", "*", previous ? "removed" : "added"),
|
||||||
|
registryId,
|
||||||
|
rowName: "*",
|
||||||
|
field: "*",
|
||||||
|
kind: previous ? "registry-removed" : "registry-added",
|
||||||
|
impact: changeImpact,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousContract =
|
||||||
|
/** @type {Record<string, unknown>} */ (previous.contract ?? {});
|
||||||
|
const currentContract =
|
||||||
|
/** @type {Record<string, unknown>} */ (current.contract ?? {});
|
||||||
|
const contractFields = new Set([
|
||||||
|
...Object.keys(previousContract),
|
||||||
|
...Object.keys(currentContract),
|
||||||
|
]);
|
||||||
|
for (const field of [...contractFields].sort()) {
|
||||||
|
const beforeHas = Object.hasOwn(previousContract, field);
|
||||||
|
const afterHas = Object.hasOwn(currentContract, field);
|
||||||
|
const beforeValue = previousContract[field];
|
||||||
|
const afterValue = currentContract[field];
|
||||||
|
if (
|
||||||
|
beforeHas &&
|
||||||
|
afterHas &&
|
||||||
|
canonicalRegistryJson(beforeValue) ===
|
||||||
|
canonicalRegistryJson(afterValue)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kind = !beforeHas
|
||||||
|
? "contract-field-added"
|
||||||
|
: !afterHas
|
||||||
|
? "contract-field-removed"
|
||||||
|
: "contract-field-changed";
|
||||||
|
impact = strongestImpact(impact, "breaking");
|
||||||
|
changes.push({
|
||||||
|
changeId: changeId(registryId, "$contract", field, kind),
|
||||||
|
registryId,
|
||||||
|
rowName: "$contract",
|
||||||
|
field,
|
||||||
|
kind,
|
||||||
|
impact: "breaking",
|
||||||
|
before: canonicalizeRegistryValue(beforeValue),
|
||||||
|
after: canonicalizeRegistryValue(afterValue),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const breakingFields = new Set(
|
||||||
|
/** @type {string[]} */ (
|
||||||
|
currentContract.breakingFields ?? []
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const beforeRows =
|
||||||
|
/** @type {Record<string, Record<string, unknown>>} */ (
|
||||||
|
previous.rows ?? {}
|
||||||
|
);
|
||||||
|
const afterRows =
|
||||||
|
/** @type {Record<string, Record<string, unknown>>} */ (current.rows ?? {});
|
||||||
|
const rowNames = new Set([
|
||||||
|
...Object.keys(beforeRows),
|
||||||
|
...Object.keys(afterRows),
|
||||||
|
]);
|
||||||
|
for (const rowName of [...rowNames].sort()) {
|
||||||
|
const beforeRow = beforeRows[rowName];
|
||||||
|
const afterRow = afterRows[rowName];
|
||||||
|
if (!beforeRow || !afterRow) {
|
||||||
|
const changeImpact = beforeRow ? "breaking" : "additive";
|
||||||
|
impact = strongestImpact(impact, changeImpact);
|
||||||
|
changes.push({
|
||||||
|
changeId: changeId(
|
||||||
|
registryId,
|
||||||
|
rowName,
|
||||||
|
"*",
|
||||||
|
beforeRow ? "removed" : "added",
|
||||||
|
),
|
||||||
|
registryId,
|
||||||
|
rowName,
|
||||||
|
field: "*",
|
||||||
|
kind: beforeRow ? "row-removed" : "row-added",
|
||||||
|
impact: changeImpact,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fields = new Set([
|
||||||
|
...Object.keys(beforeRow),
|
||||||
|
...Object.keys(afterRow),
|
||||||
|
]);
|
||||||
|
for (const field of [...fields].sort()) {
|
||||||
|
const beforeHas = Object.hasOwn(beforeRow, field);
|
||||||
|
const afterHas = Object.hasOwn(afterRow, field);
|
||||||
|
const beforeValue = beforeRow[field];
|
||||||
|
const afterValue = afterRow[field];
|
||||||
|
if (
|
||||||
|
beforeHas &&
|
||||||
|
afterHas &&
|
||||||
|
canonicalRegistryJson(beforeValue) ===
|
||||||
|
canonicalRegistryJson(afterValue)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let kind;
|
||||||
|
let changeImpact;
|
||||||
|
if (!beforeHas) {
|
||||||
|
kind = "field-added";
|
||||||
|
changeImpact = "additive";
|
||||||
|
} else if (!afterHas) {
|
||||||
|
kind = "field-removed";
|
||||||
|
changeImpact = "breaking";
|
||||||
|
} else if (valueType(beforeValue) !== valueType(afterValue)) {
|
||||||
|
kind = "field-type-changed";
|
||||||
|
changeImpact = "breaking";
|
||||||
|
} else if (
|
||||||
|
Array.isArray(beforeValue) &&
|
||||||
|
Array.isArray(afterValue) &&
|
||||||
|
beforeValue.some(
|
||||||
|
(item) =>
|
||||||
|
!afterValue.some(
|
||||||
|
(candidate) =>
|
||||||
|
canonicalRegistryJson(candidate) ===
|
||||||
|
canonicalRegistryJson(item),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
kind = "allowed-value-removed";
|
||||||
|
changeImpact = "breaking";
|
||||||
|
} else {
|
||||||
|
kind = "field-changed";
|
||||||
|
changeImpact = breakingFields.has(field)
|
||||||
|
? "breaking"
|
||||||
|
: "behavior-change";
|
||||||
|
}
|
||||||
|
impact = strongestImpact(impact, changeImpact);
|
||||||
|
changes.push({
|
||||||
|
changeId: changeId(registryId, rowName, field, kind),
|
||||||
|
registryId,
|
||||||
|
rowName,
|
||||||
|
field,
|
||||||
|
kind,
|
||||||
|
impact: changeImpact,
|
||||||
|
before: canonicalizeRegistryValue(beforeValue),
|
||||||
|
after: canonicalizeRegistryValue(afterValue),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
impact,
|
||||||
|
changes: Object.freeze(changes),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Readonly<Record<string, unknown>>} snapshot
|
||||||
|
* @param {Readonly<Record<string, unknown>>} approval
|
||||||
|
*/
|
||||||
|
export function verifyRegistryBaselineApproval(snapshot, approval) {
|
||||||
|
const actualDigest = registrySnapshotDigest(snapshot);
|
||||||
|
const approvedDigest = approval.snapshotDigest;
|
||||||
|
return Object.freeze({
|
||||||
|
passed:
|
||||||
|
approval.schemaVersion === 1 &&
|
||||||
|
typeof approval.owner === "string" &&
|
||||||
|
approval.owner.length > 0 &&
|
||||||
|
typeof approval.approvedAt === "string" &&
|
||||||
|
approvedDigest === actualDigest,
|
||||||
|
actualDigest,
|
||||||
|
approvedDigest:
|
||||||
|
typeof approvedDigest === "string" ? approvedDigest : "missing",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {ReturnType<typeof diffRegistrySnapshots>} diff
|
||||||
|
* @param {Readonly<Record<string, unknown>>} evidenceFile
|
||||||
|
*/
|
||||||
|
export function validateBreakingEvidence(diff, evidenceFile) {
|
||||||
|
const evidence = new Map(
|
||||||
|
/** @type {Array<Record<string, unknown>>} */ (
|
||||||
|
evidenceFile.changes ?? []
|
||||||
|
).map((entry) => [entry.changeId, entry]),
|
||||||
|
);
|
||||||
|
const failures = [];
|
||||||
|
for (const change of diff.changes.filter(
|
||||||
|
(entry) => entry.impact === "breaking",
|
||||||
|
)) {
|
||||||
|
const entry = evidence.get(change.changeId);
|
||||||
|
if (!entry) {
|
||||||
|
failures.push(`breaking change missing evidence: ${change.changeId}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const field of [
|
||||||
|
"versionBump",
|
||||||
|
"migration",
|
||||||
|
"compatibilityWindow",
|
||||||
|
"rollback",
|
||||||
|
"owner",
|
||||||
|
]) {
|
||||||
|
if (typeof entry[field] !== "string" || entry[field].trim().length === 0) {
|
||||||
|
failures.push(
|
||||||
|
`breaking change ${change.changeId} missing non-empty ${field}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Object.freeze({
|
||||||
|
passed: failures.length === 0,
|
||||||
|
failures: Object.freeze(failures),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { createReadStream } from "node:fs";
|
||||||
|
import { access, stat } from "node:fs/promises";
|
||||||
|
import { createServer } from "node:http";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
const root = path.resolve(process.argv[2] ?? "artifacts/storybook/static");
|
||||||
|
const port = Number(process.argv[3] ?? 6006);
|
||||||
|
const contentTypes = /** @type {Readonly<Record<string, string>>} */ ({
|
||||||
|
".css": "text/css; charset=utf-8",
|
||||||
|
".html": "text/html; charset=utf-8",
|
||||||
|
".js": "text/javascript; charset=utf-8",
|
||||||
|
".json": "application/json; charset=utf-8",
|
||||||
|
".svg": "image/svg+xml",
|
||||||
|
".png": "image/png",
|
||||||
|
});
|
||||||
|
|
||||||
|
await access(root);
|
||||||
|
const server = createServer(async (request, response) => {
|
||||||
|
try {
|
||||||
|
const url = new URL(request.url ?? "/", `http://127.0.0.1:${port}`);
|
||||||
|
const decoded = decodeURIComponent(url.pathname);
|
||||||
|
const requested = path.resolve(root, `.${decoded}`);
|
||||||
|
if (requested !== root && !requested.startsWith(`${root}${path.sep}`)) {
|
||||||
|
response.writeHead(403).end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const details = await stat(requested).catch(() => null);
|
||||||
|
const file = details?.isDirectory()
|
||||||
|
? path.join(requested, "index.html")
|
||||||
|
: requested;
|
||||||
|
await access(file);
|
||||||
|
response.writeHead(200, {
|
||||||
|
"Content-Type":
|
||||||
|
contentTypes[path.extname(file)] ?? "application/octet-stream",
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
});
|
||||||
|
createReadStream(file).pipe(response);
|
||||||
|
} catch {
|
||||||
|
response.writeHead(404).end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
server.listen(port, "127.0.0.1", () => {
|
||||||
|
process.stdout.write(`Static evidence server: ${root} on ${port}\n`);
|
||||||
|
});
|
||||||
|
for (const signal of ["SIGINT", "SIGTERM"]) {
|
||||||
|
process.on(signal, () => server.close(() => process.exit(0)));
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ const featureOwnedPaths = [
|
|||||||
featureSource,
|
featureSource,
|
||||||
featureTests,
|
featureTests,
|
||||||
"tests/e2e/reference-form.spec.js",
|
"tests/e2e/reference-form.spec.js",
|
||||||
|
"tests/mocks",
|
||||||
];
|
];
|
||||||
const copyTargets = [
|
const copyTargets = [
|
||||||
"src",
|
"src",
|
||||||
@@ -41,6 +42,7 @@ const copyTargets = [
|
|||||||
|
|
||||||
const emptyContracts = `import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.js";
|
const emptyContracts = `import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.js";
|
||||||
import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.js";
|
import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.js";
|
||||||
|
import { PLATFORM_SCHEMA_REGISTRY } from "../contracts/schema-registry.js";
|
||||||
|
|
||||||
export const INSTALLED_FEATURE_CONTRACTS =
|
export const INSTALLED_FEATURE_CONTRACTS =
|
||||||
/** @type {readonly unknown[]} */ (Object.freeze([]));
|
/** @type {readonly unknown[]} */ (Object.freeze([]));
|
||||||
@@ -48,6 +50,7 @@ export const ROUTE_REGISTRY = PLATFORM_ROUTE_REGISTRY;
|
|||||||
export const ROUTE_RUNTIME_CONTRACT = PLATFORM_ROUTE_RUNTIME_CONTRACT;
|
export const ROUTE_RUNTIME_CONTRACT = PLATFORM_ROUTE_RUNTIME_CONTRACT;
|
||||||
export const API_OPERATIONS = Object.freeze({});
|
export const API_OPERATIONS = Object.freeze({});
|
||||||
export const QUERY_REGISTRY = Object.freeze({});
|
export const QUERY_REGISTRY = Object.freeze({});
|
||||||
|
export const SCHEMA_REGISTRY = PLATFORM_SCHEMA_REGISTRY;
|
||||||
export const NAVIGATION_ROUTES = Object.freeze(
|
export const NAVIGATION_ROUTES = Object.freeze(
|
||||||
Object.values(ROUTE_REGISTRY)
|
Object.values(ROUTE_REGISTRY)
|
||||||
.filter((definition) => definition.navigationOrder !== null)
|
.filter((definition) => definition.navigationOrder !== null)
|
||||||
@@ -89,6 +92,12 @@ export function createInstalledFeatureInputs(_context: FeatureContext) {
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const emptyMessages = `export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": Object.freeze({}),
|
||||||
|
"en-US": Object.freeze({}),
|
||||||
|
});
|
||||||
|
`;
|
||||||
|
|
||||||
/** @param {string} directory @returns {Promise<string[]>} */
|
/** @param {string} directory @returns {Promise<string[]>} */
|
||||||
async function filesBelow(directory) {
|
async function filesBelow(directory) {
|
||||||
const entries = await readdir(directory, { withFileTypes: true });
|
const entries = await readdir(directory, { withFileTypes: true });
|
||||||
@@ -135,6 +144,43 @@ await writeFile(
|
|||||||
path.join(fixtureRoot, "src/features/installed-feature-adapters.ts"),
|
path.join(fixtureRoot, "src/features/installed-feature-adapters.ts"),
|
||||||
emptyAdapters,
|
emptyAdapters,
|
||||||
);
|
);
|
||||||
|
await writeFile(
|
||||||
|
path.join(fixtureRoot, "src/features/installed-feature-messages.js"),
|
||||||
|
emptyMessages,
|
||||||
|
);
|
||||||
|
const governanceFile = path.join(
|
||||||
|
fixtureRoot,
|
||||||
|
"config/contracts/registry-governance.json",
|
||||||
|
);
|
||||||
|
const removalGovernance = JSON.parse(await readFile(governanceFile, "utf8"));
|
||||||
|
removalGovernance.registries = removalGovernance.registries.map(
|
||||||
|
/** @param {Record<string, unknown>} registry */
|
||||||
|
(registry) => ({
|
||||||
|
...registry,
|
||||||
|
...(Array.isArray(registry.consumers)
|
||||||
|
? {
|
||||||
|
consumers: registry.consumers.filter(
|
||||||
|
/** @param {{path?: string}} consumer */
|
||||||
|
(consumer) =>
|
||||||
|
!consumer.path?.includes("features/reference-feature"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
...(Array.isArray(registry.consumerDirectories)
|
||||||
|
? {
|
||||||
|
consumerDirectories: registry.consumerDirectories.filter(
|
||||||
|
/** @param {string} directory */
|
||||||
|
(directory) =>
|
||||||
|
!directory.includes("features/reference-feature"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await writeFile(
|
||||||
|
governanceFile,
|
||||||
|
`${JSON.stringify(removalGovernance, null, 2)}\n`,
|
||||||
|
);
|
||||||
|
|
||||||
/** @type {string[]} */
|
/** @type {string[]} */
|
||||||
const residue = [];
|
const residue = [];
|
||||||
@@ -155,7 +201,7 @@ for (const root of ["src", "tests"]) {
|
|||||||
const checks = [
|
const checks = [
|
||||||
["typecheck", runPnpm("check:types")],
|
["typecheck", runPnpm("check:types")],
|
||||||
["architecture", runPnpm("check:architecture")],
|
["architecture", runPnpm("check:architecture")],
|
||||||
["registry", runPnpm("check:registries")],
|
["registry-structure", runPnpm("check:registries:structure")],
|
||||||
["unit-integration", runPnpm("test:all")],
|
["unit-integration", runPnpm("test:all")],
|
||||||
[
|
[
|
||||||
"home-smoke",
|
"home-smoke",
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import { registrySnapshotDigest } from "./lib/registry-compatibility.mjs";
|
||||||
|
|
||||||
|
const inputPath =
|
||||||
|
process.argv[2] ?? "artifacts/quality/registry-current-snapshot.json";
|
||||||
|
const outputPath =
|
||||||
|
process.argv[3] ?? "config/contracts/registry-baseline.json";
|
||||||
|
const owner = process.env.REGISTRY_BASELINE_OWNER;
|
||||||
|
const reason = process.env.REGISTRY_BASELINE_REASON;
|
||||||
|
|
||||||
|
if (!owner || !reason) {
|
||||||
|
process.stderr.write(
|
||||||
|
"REGISTRY_BASELINE_OWNER and REGISTRY_BASELINE_REASON are required.\n",
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = JSON.parse(await readFile(inputPath, "utf8"));
|
||||||
|
const snapshot = input.registries
|
||||||
|
? { schemaVersion: 2, registries: input.registries }
|
||||||
|
: input;
|
||||||
|
const digest = registrySnapshotDigest(snapshot);
|
||||||
|
await mkdir(path.dirname(outputPath), { recursive: true });
|
||||||
|
await writeFile(outputPath, `${JSON.stringify(snapshot, null, 2)}\n`);
|
||||||
|
await writeFile(
|
||||||
|
"config/contracts/registry-baseline.approval.json",
|
||||||
|
`${JSON.stringify(
|
||||||
|
{
|
||||||
|
schemaVersion: 1,
|
||||||
|
snapshotDigest: digest,
|
||||||
|
owner,
|
||||||
|
reason,
|
||||||
|
approvedAt: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
)}\n`,
|
||||||
|
);
|
||||||
|
process.stdout.write(`Registry baseline updated: ${digest}\n`);
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.js";
|
||||||
|
import {
|
||||||
|
projectDiagnosticRecord,
|
||||||
|
safeErrorKind,
|
||||||
|
type DiagnosticRecord,
|
||||||
|
type DiagnosticRecordInput,
|
||||||
|
} from "../../contracts/diagnostics.js";
|
||||||
|
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
|
||||||
|
|
||||||
|
export const noOpDiagnostics: DiagnosticsPort = Object.freeze({
|
||||||
|
record() {},
|
||||||
|
});
|
||||||
|
|
||||||
|
export function createDiagnosticsAdapter(
|
||||||
|
options: Readonly<{
|
||||||
|
maxEntries?: number;
|
||||||
|
now?: () => number;
|
||||||
|
sink?: (record: DiagnosticRecord) => void;
|
||||||
|
}> = {},
|
||||||
|
) {
|
||||||
|
const maxEntries = Math.max(1, options.maxEntries ?? 100);
|
||||||
|
const entries: DiagnosticRecord[] = [];
|
||||||
|
const droppedReasons = new Map<string, number>();
|
||||||
|
|
||||||
|
function drop(reason: string) {
|
||||||
|
droppedReasons.set(reason, (droppedReasons.get(reason) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function record(input: DiagnosticRecordInput) {
|
||||||
|
try {
|
||||||
|
const projected = projectDiagnosticRecord(input, options.now);
|
||||||
|
if (!projected.success) {
|
||||||
|
drop(projected.reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (entries.length >= maxEntries) {
|
||||||
|
entries.shift();
|
||||||
|
drop("queue-full");
|
||||||
|
}
|
||||||
|
entries.push(projected.record);
|
||||||
|
try {
|
||||||
|
options.sink?.(projected.record);
|
||||||
|
} catch {
|
||||||
|
drop("sink-failure");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
drop("serialization-failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
record,
|
||||||
|
entries: () => structuredClone(entries) as readonly DiagnosticRecord[],
|
||||||
|
dropped: () => Object.freeze(Object.fromEntries(droppedReasons)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
type BootSafeContext = Readonly<{
|
||||||
|
kind?: string;
|
||||||
|
buildId?: string;
|
||||||
|
configSchemaVersion?: string;
|
||||||
|
supportReference?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
let lastBootEvidence:
|
||||||
|
| Readonly<{
|
||||||
|
diagnostic: DiagnosticRecord | null;
|
||||||
|
telemetry: Readonly<Record<string, unknown>> | null;
|
||||||
|
}>
|
||||||
|
| undefined;
|
||||||
|
|
||||||
|
export function recordBootFailure(
|
||||||
|
error: unknown,
|
||||||
|
safe: BootSafeContext,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
) {
|
||||||
|
const errorKind =
|
||||||
|
typeof safe.kind === "string" ? safe.kind : safeErrorKind(error);
|
||||||
|
const attributes = {
|
||||||
|
error_kind: errorKind,
|
||||||
|
build_id: safe.buildId ?? "unknown",
|
||||||
|
config_schema_version: safe.configSchemaVersion ?? "unknown",
|
||||||
|
};
|
||||||
|
const diagnostic = projectDiagnosticRecord(
|
||||||
|
{
|
||||||
|
level: "error",
|
||||||
|
eventId: "app.boot.failed",
|
||||||
|
context: attributes,
|
||||||
|
},
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
const telemetry = projectTelemetryEvent("app.boot.failed", attributes, now);
|
||||||
|
lastBootEvidence = Object.freeze({
|
||||||
|
diagnostic: diagnostic.success ? diagnostic.record : null,
|
||||||
|
telemetry: telemetry.success ? telemetry.event : null,
|
||||||
|
});
|
||||||
|
return lastBootEvidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLastBootEvidence() {
|
||||||
|
return lastBootEvidence ? structuredClone(lastBootEvidence) : undefined;
|
||||||
|
}
|
||||||
+98
-20
@@ -14,6 +14,11 @@ import {
|
|||||||
validateOperationRequest,
|
validateOperationRequest,
|
||||||
} from "./schema-registry.js";
|
} from "./schema-registry.js";
|
||||||
import { buildRequestTarget } from "./request-builder.js";
|
import { buildRequestTarget } from "./request-builder.js";
|
||||||
|
import {
|
||||||
|
attemptBucket,
|
||||||
|
durationBucket,
|
||||||
|
statusGroup,
|
||||||
|
} from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
const noAuthSession =
|
const noAuthSession =
|
||||||
/** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({
|
/** @type {import("../../application/ports/auth-session-port.js").AuthSessionPort} */ ({
|
||||||
@@ -54,7 +59,10 @@ const noAuthSession =
|
|||||||
* timeoutMs?: number,
|
* timeoutMs?: number,
|
||||||
* maxRetryAttempts?: number,
|
* maxRetryAttempts?: number,
|
||||||
* scheduler?: Scheduler,
|
* scheduler?: Scheduler,
|
||||||
* getOperation?: typeof getApiOperation
|
* getOperation?: typeof getApiOperation,
|
||||||
|
* diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort,
|
||||||
|
* telemetry?: import("../../application/ports/telemetry-port.js").TelemetryPort,
|
||||||
|
* correlationIdFactory?: () => string
|
||||||
* }} dependencies
|
* }} dependencies
|
||||||
*/
|
*/
|
||||||
export function createHttpClient(dependencies) {
|
export function createHttpClient(dependencies) {
|
||||||
@@ -72,6 +80,11 @@ export function createHttpClient(dependencies) {
|
|||||||
const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000;
|
const defaultTimeoutMs = dependencies.timeoutMs ?? 10_000;
|
||||||
const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2;
|
const maxRetryAttempts = dependencies.maxRetryAttempts ?? 2;
|
||||||
const selectOperation = dependencies.getOperation ?? getApiOperation;
|
const selectOperation = dependencies.getOperation ?? getApiOperation;
|
||||||
|
const diagnostics = dependencies.diagnostics;
|
||||||
|
const telemetry = dependencies.telemetry;
|
||||||
|
const correlationIdFactory =
|
||||||
|
dependencies.correlationIdFactory ??
|
||||||
|
(() => `request-${Math.floor(random() * 1_000_000).toString(36)}`);
|
||||||
const scheduler =
|
const scheduler =
|
||||||
dependencies.scheduler ??
|
dependencies.scheduler ??
|
||||||
/** @type {Scheduler} */ ({
|
/** @type {Scheduler} */ ({
|
||||||
@@ -91,7 +104,8 @@ export function createHttpClient(dependencies) {
|
|||||||
* pathParams?: Record<string, string | number>,
|
* pathParams?: Record<string, string | number>,
|
||||||
* searchParams?: unknown,
|
* searchParams?: unknown,
|
||||||
* signal?: AbortSignal,
|
* signal?: AbortSignal,
|
||||||
* idempotencyKey?: string
|
* idempotencyKey?: string,
|
||||||
|
* correlationId?: string
|
||||||
* }} [legacyInput]
|
* }} [legacyInput]
|
||||||
* @returns {Promise<HttpResult>}
|
* @returns {Promise<HttpResult>}
|
||||||
*/
|
*/
|
||||||
@@ -106,9 +120,55 @@ export function createHttpClient(dependencies) {
|
|||||||
body: legacyInput.body,
|
body: legacyInput.body,
|
||||||
signal: legacyInput.signal,
|
signal: legacyInput.signal,
|
||||||
idempotencyKey: legacyInput.idempotencyKey,
|
idempotencyKey: legacyInput.idempotencyKey,
|
||||||
|
correlationId: legacyInput.correlationId,
|
||||||
}
|
}
|
||||||
: request;
|
: request;
|
||||||
const operation = selectOperation(input.operationId);
|
const operation = selectOperation(input.operationId);
|
||||||
|
const startedAt = clock.now();
|
||||||
|
const correlationId = input.correlationId ?? correlationIdFactory();
|
||||||
|
/**
|
||||||
|
* @param {HttpResult} outcome
|
||||||
|
* @param {"success" | "recovered" | "failed" | "aborted"} outcomeKind
|
||||||
|
*/
|
||||||
|
function finalize(outcome, outcomeKind) {
|
||||||
|
const error = outcome.ok ? undefined : outcome.error;
|
||||||
|
const context = {
|
||||||
|
route_id: input.routeId,
|
||||||
|
operation_id: input.operationId,
|
||||||
|
correlation_id: correlationId,
|
||||||
|
outcome: outcomeKind,
|
||||||
|
error_kind: error?.kind ?? "NONE",
|
||||||
|
http_status_group: statusGroup(error?.httpStatus),
|
||||||
|
attempt_count_bucket: attemptBucket(
|
||||||
|
error?.attemptCount ?? retryCount + 1,
|
||||||
|
),
|
||||||
|
duration_bucket: durationBucket(clock.now() - startedAt),
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
diagnostics?.record({
|
||||||
|
level: error ? "warn" : "info",
|
||||||
|
eventId: "http.request.completed",
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Diagnostics cannot change the HTTP result.
|
||||||
|
}
|
||||||
|
if (error && outcomeKind !== "aborted") {
|
||||||
|
try {
|
||||||
|
telemetry?.emit("api.request.failed", {
|
||||||
|
error_kind: context.error_kind,
|
||||||
|
http_status_group: context.http_status_group,
|
||||||
|
attempt_count_bucket: context.attempt_count_bucket,
|
||||||
|
route_id: context.route_id,
|
||||||
|
operation_id: context.operation_id,
|
||||||
|
duration_bucket: context.duration_bucket,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Telemetry cannot change the HTTP result.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
const logicalIdempotencyKey =
|
const logicalIdempotencyKey =
|
||||||
operation.idempotency === "keyed"
|
operation.idempotency === "keyed"
|
||||||
? input.idempotencyKey ?? idempotencyKeyFactory()
|
? input.idempotencyKey ?? idempotencyKeyFactory()
|
||||||
@@ -126,28 +186,40 @@ export function createHttpClient(dependencies) {
|
|||||||
idempotencyKey: logicalIdempotencyKey,
|
idempotencyKey: logicalIdempotencyKey,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (outcome.ok) return outcome;
|
if (outcome.ok) {
|
||||||
|
return finalize(
|
||||||
|
outcome,
|
||||||
|
retryCount > 0 || recoveryUsed ? "recovered" : "success",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
|
if (outcome.error.httpStatus === 401 && !recoveryUsed) {
|
||||||
recoveryUsed = true;
|
recoveryUsed = true;
|
||||||
const recovered = await recoverSession(authSession, operation, outcome.error);
|
const recovered = await recoverSession(
|
||||||
if (!recovered.ok) return recovered;
|
authSession,
|
||||||
|
operation,
|
||||||
|
outcome.error,
|
||||||
|
);
|
||||||
|
if (!recovered.ok) return finalize(recovered, "failed");
|
||||||
if (operation.idempotency === "none") {
|
if (operation.idempotency === "none") {
|
||||||
return {
|
return finalize(
|
||||||
ok: false,
|
{
|
||||||
error: {
|
ok: false,
|
||||||
...outcome.error,
|
error: {
|
||||||
retryable: false,
|
...outcome.error,
|
||||||
action: "retry",
|
retryable: false,
|
||||||
|
action: "retry",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
"failed",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (outcome.error.httpStatus === 401 && recoveryUsed) {
|
if (outcome.error.httpStatus === 401 && recoveryUsed) {
|
||||||
authSession.onUnauthenticated();
|
authSession.onUnauthenticated();
|
||||||
return outcome;
|
return finalize(outcome, "failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
@@ -158,7 +230,10 @@ export function createHttpClient(dependencies) {
|
|||||||
maxRetryAttempts,
|
maxRetryAttempts,
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
return outcome;
|
return finalize(
|
||||||
|
outcome,
|
||||||
|
outcome.error.kind === "REQUEST_ABORTED" ? "aborted" : "failed",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const delay = retryDelay(outcome.error, retryCount, random, clock.now());
|
const delay = retryDelay(outcome.error, retryCount, random, clock.now());
|
||||||
@@ -167,12 +242,15 @@ export function createHttpClient(dependencies) {
|
|||||||
try {
|
try {
|
||||||
await clock.sleep(delay, input.signal);
|
await clock.sleep(delay, input.signal);
|
||||||
} catch {
|
} catch {
|
||||||
return {
|
return finalize(
|
||||||
ok: false,
|
{
|
||||||
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
|
ok: false,
|
||||||
code: "REQUEST_ABORTED",
|
error: failure("REQUEST_ABORTED", input.operationId, retryCount, {
|
||||||
}),
|
code: "REQUEST_ABORTED",
|
||||||
};
|
}),
|
||||||
|
},
|
||||||
|
"aborted",
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ export type OperationRequestInput = Readonly<{
|
|||||||
body?: unknown;
|
body?: unknown;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
idempotencyKey?: string;
|
idempotencyKey?: string;
|
||||||
|
correlationId?: string;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
export type RequestTargetResult =
|
export type RequestTargetResult =
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { QueryClient } from "@tanstack/react-query";
|
import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query";
|
||||||
|
|
||||||
import { createFailure } from "../../contracts/errors.js";
|
import { createFailure } from "../../contracts/errors.js";
|
||||||
|
import { safeErrorKind } from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
||||||
staleTime: 30_000,
|
staleTime: 30_000,
|
||||||
@@ -11,8 +12,32 @@ export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
|||||||
persistence: false,
|
persistence: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
export function createQueryClient() {
|
/**
|
||||||
|
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
|
||||||
|
*/
|
||||||
|
export function createQueryClient(dependencies = {}) {
|
||||||
|
/** @param {string} operation @param {unknown} error */
|
||||||
|
function report(operation, error) {
|
||||||
|
try {
|
||||||
|
dependencies.diagnostics?.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "cache.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation,
|
||||||
|
error_kind: safeErrorKind(error),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Query behavior remains independent from diagnostics.
|
||||||
|
}
|
||||||
|
}
|
||||||
return new QueryClient({
|
return new QueryClient({
|
||||||
|
queryCache: new QueryCache({
|
||||||
|
onError: (error) => report("query", error),
|
||||||
|
}),
|
||||||
|
mutationCache: new MutationCache({
|
||||||
|
onError: (error) => report("mutation", error),
|
||||||
|
}),
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
queries: {
|
queries: {
|
||||||
staleTime: QUERY_CACHE_DEFAULTS.staleTime,
|
staleTime: QUERY_CACHE_DEFAULTS.staleTime,
|
||||||
@@ -29,15 +54,16 @@ export function createQueryClient() {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {QueryClient} queryClient
|
* @param {QueryClient} queryClient
|
||||||
|
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
|
||||||
* @returns {import("../../application/ports/query-cache-port.js").QueryCachePort}
|
* @returns {import("../../application/ports/query-cache-port.js").QueryCachePort}
|
||||||
*/
|
*/
|
||||||
export function createQueryCacheAdapter(queryClient) {
|
export function createQueryCacheAdapter(queryClient, dependencies = {}) {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
read(key) {
|
read(key) {
|
||||||
try {
|
try {
|
||||||
return { ok: true, value: queryClient.getQueryData(key) };
|
return { ok: true, value: queryClient.getQueryData(key) };
|
||||||
} catch {
|
} catch {
|
||||||
return cacheFailure("read", key);
|
return cacheFailure("read", key, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
write(key, value) {
|
write(key, value) {
|
||||||
@@ -45,7 +71,7 @@ export function createQueryCacheAdapter(queryClient) {
|
|||||||
queryClient.setQueryData(key, structuredClone(value));
|
queryClient.setQueryData(key, structuredClone(value));
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch {
|
||||||
return cacheFailure("write", key);
|
return cacheFailure("write", key, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async invalidate(namespace) {
|
async invalidate(namespace) {
|
||||||
@@ -53,15 +79,31 @@ export function createQueryCacheAdapter(queryClient) {
|
|||||||
await queryClient.invalidateQueries({ queryKey: namespace, exact: false });
|
await queryClient.invalidateQueries({ queryKey: namespace, exact: false });
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch {
|
||||||
return cacheFailure("invalidate", namespace);
|
return cacheFailure("invalidate", namespace, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {string} phase @param {readonly unknown[]} key */
|
/**
|
||||||
function cacheFailure(phase, key) {
|
* @param {string} phase
|
||||||
|
* @param {readonly unknown[]} key
|
||||||
|
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||||
|
*/
|
||||||
|
function cacheFailure(phase, key, diagnostics) {
|
||||||
const namespace = typeof key[0] === "string" ? key[0] : "unknown";
|
const namespace = typeof key[0] === "string" ? key[0] : "unknown";
|
||||||
|
try {
|
||||||
|
diagnostics?.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "cache.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation: phase,
|
||||||
|
error_kind: "QUERY_CACHE_FAILURE",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Cache behavior remains independent from diagnostics.
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
ok: /** @type {false} */ (false),
|
ok: /** @type {false} */ (false),
|
||||||
error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, {
|
error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, {
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ import { getStorageDefinition } from "../../contracts/storage-keys.js";
|
|||||||
* @param {{
|
* @param {{
|
||||||
* localStorage?: Storage,
|
* localStorage?: Storage,
|
||||||
* sessionStorage?: Storage,
|
* sessionStorage?: Storage,
|
||||||
* now?: () => number
|
* now?: () => number,
|
||||||
|
* diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort
|
||||||
* }} [dependencies]
|
* }} [dependencies]
|
||||||
* @returns {import("../../application/ports/storage-port.js").StoragePort}
|
* @returns {import("../../application/ports/storage-port.js").StoragePort}
|
||||||
*/
|
*/
|
||||||
@@ -26,7 +27,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
try {
|
try {
|
||||||
definition = getStorageDefinition(logicalName);
|
definition = getStorageDefinition(logicalName);
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("read", logicalName);
|
return unavailable("read", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
|
|
||||||
const backend = backendFor(definition.backend);
|
const backend = backendFor(definition.backend);
|
||||||
@@ -50,7 +51,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
}
|
}
|
||||||
return { ok: true, value: structuredClone(envelope.value) };
|
return { ok: true, value: structuredClone(envelope.value) };
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("read", logicalName);
|
return unavailable("read", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -59,7 +60,7 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
try {
|
try {
|
||||||
definition = getStorageDefinition(logicalName);
|
definition = getStorageDefinition(logicalName);
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("write", logicalName);
|
return unavailable("write", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
|
|
||||||
const expiresAt =
|
const expiresAt =
|
||||||
@@ -82,12 +83,24 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
|
|
||||||
if (definition.quotaFallback === "memory") {
|
if (definition.quotaFallback === "memory") {
|
||||||
memory.set(definition.physicalKey, structuredClone(value));
|
memory.set(definition.physicalKey, structuredClone(value));
|
||||||
|
recordStorageFailure(
|
||||||
|
dependencies.diagnostics,
|
||||||
|
"write",
|
||||||
|
logicalName,
|
||||||
|
quota,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: storageFailure(quota, "write", logicalName),
|
error: storageFailure(quota, "write", logicalName),
|
||||||
fallback: "memory",
|
fallback: "memory",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
recordStorageFailure(
|
||||||
|
dependencies.diagnostics,
|
||||||
|
"write",
|
||||||
|
logicalName,
|
||||||
|
quota,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: storageFailure(quota, "write", logicalName),
|
error: storageFailure(quota, "write", logicalName),
|
||||||
@@ -101,14 +114,14 @@ export function createBrowserStorageAdapter(dependencies = {}) {
|
|||||||
try {
|
try {
|
||||||
definition = getStorageDefinition(logicalName);
|
definition = getStorageDefinition(logicalName);
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("remove", logicalName);
|
return unavailable("remove", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
backendFor(definition.backend)?.removeItem(definition.physicalKey);
|
backendFor(definition.backend)?.removeItem(definition.physicalKey);
|
||||||
memory.delete(definition.physicalKey);
|
memory.delete(definition.physicalKey);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch {
|
||||||
return unavailable("remove", logicalName);
|
return unavailable("remove", logicalName, dependencies.diagnostics);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -128,10 +141,38 @@ function storageFailure(quota, phase, logicalName) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param {string} phase @param {string} logicalName */
|
/**
|
||||||
function unavailable(phase, logicalName) {
|
* @param {string} phase
|
||||||
|
* @param {string} logicalName
|
||||||
|
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||||
|
*/
|
||||||
|
function unavailable(phase, logicalName, diagnostics) {
|
||||||
|
recordStorageFailure(diagnostics, phase, logicalName, false);
|
||||||
return {
|
return {
|
||||||
ok: /** @type {false} */ (false),
|
ok: /** @type {false} */ (false),
|
||||||
error: storageFailure(false, phase, logicalName),
|
error: storageFailure(false, phase, logicalName),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||||
|
* @param {string} phase
|
||||||
|
* @param {string} logicalName
|
||||||
|
* @param {boolean} quota
|
||||||
|
*/
|
||||||
|
function recordStorageFailure(diagnostics, phase, logicalName, quota) {
|
||||||
|
try {
|
||||||
|
diagnostics?.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "storage.operation.failed",
|
||||||
|
context: {
|
||||||
|
operation: `${phase}:${logicalName}`,
|
||||||
|
error_kind: quota
|
||||||
|
? "STORAGE_QUOTA_EXCEEDED"
|
||||||
|
: "STORAGE_UNAVAILABLE",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Storage behavior remains independent from diagnostics.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
|
import { projectTelemetryEvent } from "../../contracts/telemetry.js";
|
||||||
|
import { queueSizeBucket } from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
export const noOpTelemetry = Object.freeze({
|
export const noOpTelemetry = Object.freeze({
|
||||||
emit: () => {},
|
emit: () => {},
|
||||||
|
flush: async () => {},
|
||||||
|
pendingCount: () => 0,
|
||||||
|
droppedCount: () => 0,
|
||||||
|
dropReasons: () => Object.freeze({}),
|
||||||
|
deliveryEvidence: () => null,
|
||||||
|
dispose: () => {},
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -10,22 +17,20 @@ export const noOpTelemetry = Object.freeze({
|
|||||||
* endpoint?: string,
|
* endpoint?: string,
|
||||||
* fetcher?: typeof fetch,
|
* fetcher?: typeof fetch,
|
||||||
* maxQueue?: number,
|
* maxQueue?: number,
|
||||||
* schedule?: (callback: () => void) => void
|
* schedule?: (callback: () => void) => void,
|
||||||
|
* now?: () => number,
|
||||||
|
* onDrop?: (event: Readonly<Record<string, unknown>>) => void,
|
||||||
|
* lifecycle?: Pick<EventTarget, "addEventListener" | "removeEventListener">
|
||||||
* }} options
|
* }} options
|
||||||
*/
|
*/
|
||||||
export function createTelemetryAdapter(options) {
|
export function createTelemetryAdapter(options) {
|
||||||
if (!options.enabled || !options.endpoint) {
|
if (!options.enabled || !options.endpoint) {
|
||||||
return Object.freeze({
|
return noOpTelemetry;
|
||||||
...noOpTelemetry,
|
|
||||||
flush: async () => {},
|
|
||||||
pendingCount: () => 0,
|
|
||||||
droppedCount: () => 0,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const endpoint = /** @type {string} */ (options.endpoint);
|
const endpoint = /** @type {string} */ (options.endpoint);
|
||||||
const fetcher = options.fetcher ?? fetch;
|
const fetcher = options.fetcher ?? fetch;
|
||||||
const maxQueue = options.maxQueue ?? 100;
|
const maxQueue = Math.max(1, options.maxQueue ?? 100);
|
||||||
const schedule = options.schedule ?? queueMicrotask;
|
const schedule = options.schedule ?? queueMicrotask;
|
||||||
const queue =
|
const queue =
|
||||||
/** @type {Array<{eventName: string, attributes: Readonly<Record<string, unknown>>}>} */ (
|
/** @type {Array<{eventName: string, attributes: Readonly<Record<string, unknown>>}>} */ (
|
||||||
@@ -34,18 +39,63 @@ export function createTelemetryAdapter(options) {
|
|||||||
let scheduled = false;
|
let scheduled = false;
|
||||||
let flushing = false;
|
let flushing = false;
|
||||||
let dropped = 0;
|
let dropped = 0;
|
||||||
|
const dropReasons = new Map();
|
||||||
|
let lastDeliveryEvidence =
|
||||||
|
/** @type {Readonly<Record<string, unknown>> | null} */ (null);
|
||||||
|
const lifecycle =
|
||||||
|
options.lifecycle ??
|
||||||
|
(typeof globalThis.addEventListener === "function" &&
|
||||||
|
typeof globalThis.removeEventListener === "function"
|
||||||
|
? globalThis
|
||||||
|
: undefined);
|
||||||
|
|
||||||
|
/** @param {string} reason @param {number} count */
|
||||||
|
function recordDrop(reason, count = 1) {
|
||||||
|
const safeReason =
|
||||||
|
{
|
||||||
|
"queue-full": "queue-full",
|
||||||
|
"sink-failure": "sink-failure",
|
||||||
|
"serialization-failure": "serialization-failure",
|
||||||
|
"unknown-attributes": "invalid-context",
|
||||||
|
"invalid-attribute-value": "invalid-context",
|
||||||
|
"missing-required-attributes": "invalid-context",
|
||||||
|
"unregistered-event": "invalid-event",
|
||||||
|
}[reason] ?? "invalid-event";
|
||||||
|
dropped += count;
|
||||||
|
dropReasons.set(safeReason, (dropReasons.get(safeReason) ?? 0) + count);
|
||||||
|
const internal = projectTelemetryEvent(
|
||||||
|
"telemetry.delivery.dropped",
|
||||||
|
{
|
||||||
|
reason: safeReason,
|
||||||
|
queue_size_bucket: queueSizeBucket(queue.length),
|
||||||
|
},
|
||||||
|
options.now,
|
||||||
|
);
|
||||||
|
if (internal.success) {
|
||||||
|
lastDeliveryEvidence = internal.event;
|
||||||
|
try {
|
||||||
|
options.onDrop?.(internal.event);
|
||||||
|
} catch {
|
||||||
|
// Drop observers are deliberately nonrecursive.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** @param {string} eventName @param {Record<string, unknown>} attributes */
|
/** @param {string} eventName @param {Record<string, unknown>} attributes */
|
||||||
function emit(eventName, attributes) {
|
function emit(eventName, attributes) {
|
||||||
const projected = projectTelemetryEvent(eventName, attributes);
|
const projected = projectTelemetryEvent(
|
||||||
|
eventName,
|
||||||
|
attributes,
|
||||||
|
options.now,
|
||||||
|
);
|
||||||
if (!projected.success) {
|
if (!projected.success) {
|
||||||
dropped += 1;
|
recordDrop(projected.reason);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (queue.length >= maxQueue) {
|
if (queue.length >= maxQueue) {
|
||||||
queue.shift();
|
queue.shift();
|
||||||
dropped += 1;
|
recordDrop("queue-full");
|
||||||
}
|
}
|
||||||
queue.push(projected.event);
|
queue.push(projected.event);
|
||||||
|
|
||||||
@@ -69,19 +119,32 @@ export function createTelemetryAdapter(options) {
|
|||||||
body: JSON.stringify({ events: batch }),
|
body: JSON.stringify({ events: batch }),
|
||||||
keepalive: true,
|
keepalive: true,
|
||||||
});
|
});
|
||||||
if (!response.ok) dropped += batch.length;
|
if (!response.ok) recordDrop("sink-failure", batch.length);
|
||||||
} catch {
|
} catch {
|
||||||
dropped += batch.length;
|
recordDrop("sink-failure", batch.length);
|
||||||
} finally {
|
} finally {
|
||||||
flushing = false;
|
flushing = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const flushBeforePageExit = () => {
|
||||||
|
void flush();
|
||||||
|
};
|
||||||
|
lifecycle?.addEventListener("pagehide", flushBeforePageExit);
|
||||||
|
|
||||||
|
function dispose() {
|
||||||
|
lifecycle?.removeEventListener("pagehide", flushBeforePageExit);
|
||||||
|
}
|
||||||
|
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
emit,
|
emit,
|
||||||
flush,
|
flush,
|
||||||
pendingCount: () => queue.length,
|
pendingCount: () => queue.length,
|
||||||
droppedCount: () => dropped,
|
droppedCount: () => dropped,
|
||||||
|
dropReasons: () => Object.freeze(Object.fromEntries(dropReasons)),
|
||||||
|
deliveryEvidence: () =>
|
||||||
|
lastDeliveryEvidence ? structuredClone(lastDeliveryEvidence) : null,
|
||||||
|
dispose,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type {
|
|||||||
ApplicationApi,
|
ApplicationApi,
|
||||||
ColorSchemePreference,
|
ColorSchemePreference,
|
||||||
RenderFailureReport,
|
RenderFailureReport,
|
||||||
|
RouteChangedReport,
|
||||||
} from "./ports/in/application-api.js";
|
} from "./ports/in/application-api.js";
|
||||||
import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js";
|
import type { ApplicationOutputPorts } from "./ports/out/application-output-ports.js";
|
||||||
import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.js";
|
import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.js";
|
||||||
@@ -43,7 +44,20 @@ export function createApplication(
|
|||||||
const diagnostics = Object.freeze({
|
const diagnostics = Object.freeze({
|
||||||
reportRenderFailure(report: RenderFailureReport) {
|
reportRenderFailure(report: RenderFailureReport) {
|
||||||
try {
|
try {
|
||||||
outputPorts.diagnostics.emit("ui.render.failed", {
|
outputPorts.diagnostics.record({
|
||||||
|
level: "error",
|
||||||
|
eventId: "ui.render.failed",
|
||||||
|
context: {
|
||||||
|
route_id: report.routeId,
|
||||||
|
build_id: report.buildId,
|
||||||
|
component_boundary: report.boundaryName,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Diagnostics are best-effort and cannot become an application failure.
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
outputPorts.telemetry.emit("ui.render.failed", {
|
||||||
route_id: report.routeId,
|
route_id: report.routeId,
|
||||||
build_id: report.buildId,
|
build_id: report.buildId,
|
||||||
component_boundary: report.boundaryName,
|
component_boundary: report.boundaryName,
|
||||||
@@ -52,6 +66,20 @@ export function createApplication(
|
|||||||
// Diagnostics are best-effort and cannot become an application failure.
|
// Diagnostics are best-effort and cannot become an application failure.
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
reportRouteChanged(report: RouteChangedReport) {
|
||||||
|
try {
|
||||||
|
outputPorts.diagnostics.record({
|
||||||
|
level: "info",
|
||||||
|
eventId: "route.changed",
|
||||||
|
context: {
|
||||||
|
route_id: report.routeId,
|
||||||
|
build_id: report.buildId,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Diagnostics are best-effort and cannot become navigation failure.
|
||||||
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const runtime = Object.freeze({
|
const runtime = Object.freeze({
|
||||||
@@ -74,6 +102,37 @@ export function createApplication(
|
|||||||
try {
|
try {
|
||||||
const current = await outputPorts.releaseInfo.getCurrent();
|
const current = await outputPorts.releaseInfo.getCurrent();
|
||||||
const active = await outputPorts.releaseInfo.refresh();
|
const active = await outputPorts.releaseInfo.refresh();
|
||||||
|
if (
|
||||||
|
current.buildId !== active.buildId ||
|
||||||
|
current.releaseId !== active.releaseId
|
||||||
|
) {
|
||||||
|
const mismatchKind =
|
||||||
|
current.buildId !== active.buildId
|
||||||
|
? "BUILD_MISMATCH"
|
||||||
|
: "RELEASE_MISMATCH";
|
||||||
|
try {
|
||||||
|
outputPorts.diagnostics.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "release.mismatch.detected",
|
||||||
|
context: {
|
||||||
|
build_id: current.buildId,
|
||||||
|
active_release_id: active.releaseId,
|
||||||
|
mismatch_kind: mismatchKind,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Recovery remains independent from diagnostics.
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
outputPorts.telemetry.emit("release.mismatch.detected", {
|
||||||
|
build_id: current.buildId,
|
||||||
|
active_release_id: active.releaseId,
|
||||||
|
mismatch_kind: mismatchKind,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Recovery remains independent from telemetry.
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!active.routeChunks[input.chunkId]) {
|
if (!active.routeChunks[input.chunkId]) {
|
||||||
return {
|
return {
|
||||||
action: "support" as const,
|
action: "support" as const,
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import type { DiagnosticRecordInput } from "../../contracts/diagnostics.js";
|
||||||
|
|
||||||
|
export type DiagnosticsPort = Readonly<{
|
||||||
|
record(input: DiagnosticRecordInput): void;
|
||||||
|
}>;
|
||||||
@@ -11,6 +11,11 @@ export type RenderFailureReport = Readonly<{
|
|||||||
boundaryName: "route" | "feature";
|
boundaryName: "route" | "feature";
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
|
export type RouteChangedReport = Readonly<{
|
||||||
|
routeId: string;
|
||||||
|
buildId: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
export type ReleaseSummary = Readonly<{
|
export type ReleaseSummary = Readonly<{
|
||||||
buildId: string;
|
buildId: string;
|
||||||
releaseId: string;
|
releaseId: string;
|
||||||
@@ -34,6 +39,7 @@ export type ApplicationApi = Readonly<{
|
|||||||
}>;
|
}>;
|
||||||
diagnostics: Readonly<{
|
diagnostics: Readonly<{
|
||||||
reportRenderFailure(report: RenderFailureReport): void;
|
reportRenderFailure(report: RenderFailureReport): void;
|
||||||
|
reportRouteChanged(report: RouteChangedReport): void;
|
||||||
}>;
|
}>;
|
||||||
runtime: Readonly<{
|
runtime: Readonly<{
|
||||||
getReleaseSummary(): Promise<ReleaseSummary>;
|
getReleaseSummary(): Promise<ReleaseSummary>;
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { AuthSessionPort } from "../auth-session-port.js";
|
|||||||
import type { ReleaseInfoPort } from "../release-info-port.js";
|
import type { ReleaseInfoPort } from "../release-info-port.js";
|
||||||
import type { StoragePort } from "../storage-port.js";
|
import type { StoragePort } from "../storage-port.js";
|
||||||
import type { TelemetryPort } from "../telemetry-port.js";
|
import type { TelemetryPort } from "../telemetry-port.js";
|
||||||
|
import type { DiagnosticsPort } from "../diagnostics-port.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Capabilities required by application use cases. Implementations live in
|
* Capabilities required by application use cases. Implementations live in
|
||||||
@@ -13,7 +14,8 @@ export type ApplicationOutputPorts = Readonly<{
|
|||||||
"getState" | "subscribe" | "beginSignIn" | "signOut" | "recover"
|
"getState" | "subscribe" | "beginSignIn" | "signOut" | "recover"
|
||||||
>;
|
>;
|
||||||
preferences: StoragePort;
|
preferences: StoragePort;
|
||||||
diagnostics: TelemetryPort;
|
diagnostics: DiagnosticsPort;
|
||||||
|
telemetry: TelemetryPort;
|
||||||
releaseInfo: ReleaseInfoPort;
|
releaseInfo: ReleaseInfoPort;
|
||||||
navigation: Readonly<{ reload(): void }>;
|
navigation: Readonly<{ reload(): void }>;
|
||||||
}>;
|
}>;
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ export type { QueryCachePort } from "../query-cache-port.js";
|
|||||||
export type { ReleaseInfoPort } from "../release-info-port.js";
|
export type { ReleaseInfoPort } from "../release-info-port.js";
|
||||||
export type { StoragePort } from "../storage-port.js";
|
export type { StoragePort } from "../storage-port.js";
|
||||||
export type { TelemetryPort } from "../telemetry-port.js";
|
export type { TelemetryPort } from "../telemetry-port.js";
|
||||||
|
export type { DiagnosticsPort } from "../diagnostics-port.js";
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
/**
|
|
||||||
* @typedef {{ emit(eventName: string, attributes: Record<string, unknown>): void }} TelemetryPort
|
|
||||||
*/
|
|
||||||
|
|
||||||
export {};
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import type { TelemetryEventName } from "../../contracts/telemetry.js";
|
||||||
|
|
||||||
|
export type { TelemetryEventName };
|
||||||
|
|
||||||
|
export type TelemetryPort = Readonly<{
|
||||||
|
emit(
|
||||||
|
eventName: TelemetryEventName,
|
||||||
|
attributes: Record<string, unknown>,
|
||||||
|
): void;
|
||||||
|
}>;
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { createRoot } from "react-dom/client";
|
import { createRoot } from "react-dom/client";
|
||||||
|
|
||||||
|
import { recordBootFailure } from "../adapters/diagnostics/bounded-diagnostics.js";
|
||||||
import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx";
|
import { BootErrorShell } from "../presentation/boundaries/boot-error-shell.jsx";
|
||||||
import { createRuntimeComposition } from "./create-runtime-composition.js";
|
import { createRuntimeComposition } from "./create-runtime-composition.js";
|
||||||
import { initializeColorScheme } from "./initialize-color-scheme.js";
|
import { initializeColorScheme } from "./initialize-color-scheme.js";
|
||||||
@@ -19,6 +20,8 @@ const root = createRoot(rootElement);
|
|||||||
async function boot() {
|
async function boot() {
|
||||||
try {
|
try {
|
||||||
const composition = await createRuntimeComposition();
|
const composition = await createRuntimeComposition();
|
||||||
|
document.documentElement.dataset.buildId = composition.release.buildId;
|
||||||
|
document.documentElement.dataset.releaseId = composition.release.releaseId;
|
||||||
initializeColorScheme(composition.application.preferences);
|
initializeColorScheme(composition.application.preferences);
|
||||||
root.render(<RuntimeApplication composition={composition} />);
|
root.render(<RuntimeApplication composition={composition} />);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -27,6 +30,7 @@ async function boot() {
|
|||||||
? error.safe
|
? error.safe
|
||||||
: { supportReference: "boot:unknown" };
|
: { supportReference: "boot:unknown" };
|
||||||
|
|
||||||
|
recordBootFailure(error, safe);
|
||||||
root.render(<BootErrorShell {...safe} />);
|
root.render(<BootErrorShell {...safe} />);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
createUnavailableSessionAdapter,
|
createUnavailableSessionAdapter,
|
||||||
} from "../adapters/auth/external-session-adapter.js";
|
} from "../adapters/auth/external-session-adapter.js";
|
||||||
import { createHttpClient } from "../adapters/http/client.js";
|
import { createHttpClient } from "../adapters/http/client.js";
|
||||||
|
import { createDiagnosticsAdapter } from "../adapters/diagnostics/bounded-diagnostics.js";
|
||||||
import {
|
import {
|
||||||
createQueryClient,
|
createQueryClient,
|
||||||
} from "../adapters/query-cache/tanstack-query-cache.js";
|
} from "../adapters/query-cache/tanstack-query-cache.js";
|
||||||
@@ -53,6 +54,8 @@ function storageOrUndefined(value) {
|
|||||||
* fetcher?: typeof fetch,
|
* fetcher?: typeof fetch,
|
||||||
* clock?: import("../application/ports/clock-port.js").ClockPort,
|
* clock?: import("../application/ports/clock-port.js").ClockPort,
|
||||||
* scheduler?: Parameters<typeof createHttpClient>[0]["scheduler"]
|
* scheduler?: Parameters<typeof createHttpClient>[0]["scheduler"]
|
||||||
|
* diagnostics?: Parameters<typeof createHttpClient>[0]["diagnostics"],
|
||||||
|
* telemetry?: Parameters<typeof createHttpClient>[0]["telemetry"]
|
||||||
* }} context
|
* }} context
|
||||||
*/
|
*/
|
||||||
export function createRuntimeHttpClient(context, contract = {}) {
|
export function createRuntimeHttpClient(context, contract = {}) {
|
||||||
@@ -64,6 +67,8 @@ export function createRuntimeHttpClient(context, contract = {}) {
|
|||||||
fetcher: context.fetcher,
|
fetcher: context.fetcher,
|
||||||
clock: context.clock,
|
clock: context.clock,
|
||||||
scheduler: context.scheduler,
|
scheduler: context.scheduler,
|
||||||
|
diagnostics: context.diagnostics,
|
||||||
|
telemetry: context.telemetry,
|
||||||
...contract,
|
...contract,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -86,15 +91,28 @@ export async function createRuntimeAdapters(context) {
|
|||||||
: externalOwner
|
: externalOwner
|
||||||
? createExternalAuthSessionAdapter(externalOwner)
|
? createExternalAuthSessionAdapter(externalOwner)
|
||||||
: createUnavailableSessionAdapter();
|
: createUnavailableSessionAdapter();
|
||||||
const queryClient = createQueryClient();
|
const diagnostics = createDiagnosticsAdapter();
|
||||||
const storage = createBrowserStorageAdapter({
|
|
||||||
localStorage: storageOrUndefined(host.localStorage),
|
|
||||||
sessionStorage: storageOrUndefined(host.sessionStorage),
|
|
||||||
});
|
|
||||||
const telemetry = createTelemetryAdapter({
|
const telemetry = createTelemetryAdapter({
|
||||||
enabled: config.TELEMETRY_ENABLED,
|
enabled: config.TELEMETRY_ENABLED,
|
||||||
endpoint: config.TELEMETRY_ENDPOINT,
|
endpoint: config.TELEMETRY_ENDPOINT,
|
||||||
fetcher: context.fetcher,
|
fetcher: context.fetcher,
|
||||||
|
onDrop(event) {
|
||||||
|
const attributes =
|
||||||
|
event.attributes && typeof event.attributes === "object"
|
||||||
|
? event.attributes
|
||||||
|
: {};
|
||||||
|
diagnostics.record({
|
||||||
|
level: "warn",
|
||||||
|
eventId: "telemetry.delivery.dropped",
|
||||||
|
context: /** @type {Record<string, unknown>} */ (attributes),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const queryClient = createQueryClient({ diagnostics });
|
||||||
|
const storage = createBrowserStorageAdapter({
|
||||||
|
localStorage: storageOrUndefined(host.localStorage),
|
||||||
|
sessionStorage: storageOrUndefined(host.sessionStorage),
|
||||||
|
diagnostics,
|
||||||
});
|
});
|
||||||
const releaseInfo = Object.freeze({
|
const releaseInfo = Object.freeze({
|
||||||
async getCurrent() {
|
async getCurrent() {
|
||||||
@@ -125,6 +143,8 @@ export async function createRuntimeAdapters(context) {
|
|||||||
runtime: context.runtime,
|
runtime: context.runtime,
|
||||||
authSession,
|
authSession,
|
||||||
fetcher: context.fetcher,
|
fetcher: context.fetcher,
|
||||||
|
diagnostics,
|
||||||
|
telemetry,
|
||||||
},
|
},
|
||||||
contract,
|
contract,
|
||||||
),
|
),
|
||||||
@@ -134,7 +154,8 @@ export async function createRuntimeAdapters(context) {
|
|||||||
outputPorts: Object.freeze({
|
outputPorts: Object.freeze({
|
||||||
session: authSession,
|
session: authSession,
|
||||||
preferences: storage,
|
preferences: storage,
|
||||||
diagnostics: telemetry,
|
diagnostics,
|
||||||
|
telemetry,
|
||||||
releaseInfo,
|
releaseInfo,
|
||||||
navigation,
|
navigation,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -0,0 +1,183 @@
|
|||||||
|
export const DIAGNOSTIC_LEVELS = Object.freeze([
|
||||||
|
"debug",
|
||||||
|
"info",
|
||||||
|
"warn",
|
||||||
|
"error",
|
||||||
|
] as const);
|
||||||
|
export type DiagnosticLevel = (typeof DIAGNOSTIC_LEVELS)[number];
|
||||||
|
|
||||||
|
export const DIAGNOSTIC_EVENT_REGISTRY = Object.freeze({
|
||||||
|
"app.boot.failed": Object.freeze({ level: "error" }),
|
||||||
|
"http.request.completed": Object.freeze({ level: "info" }),
|
||||||
|
"cache.operation.failed": Object.freeze({ level: "warn" }),
|
||||||
|
"storage.operation.failed": Object.freeze({ level: "warn" }),
|
||||||
|
"route.changed": Object.freeze({ level: "info" }),
|
||||||
|
"ui.render.failed": Object.freeze({ level: "error" }),
|
||||||
|
"release.mismatch.detected": Object.freeze({ level: "warn" }),
|
||||||
|
"telemetry.delivery.dropped": Object.freeze({ level: "warn" }),
|
||||||
|
});
|
||||||
|
export type DiagnosticEventId = keyof typeof DIAGNOSTIC_EVENT_REGISTRY;
|
||||||
|
|
||||||
|
export const DIAGNOSTIC_CONTEXT_ALLOWLIST = Object.freeze([
|
||||||
|
"app_version",
|
||||||
|
"build_id",
|
||||||
|
"release_id",
|
||||||
|
"active_release_id",
|
||||||
|
"config_schema_version",
|
||||||
|
"api_contract_version",
|
||||||
|
"route_id",
|
||||||
|
"operation_id",
|
||||||
|
"correlation_id",
|
||||||
|
"error_kind",
|
||||||
|
"outcome",
|
||||||
|
"http_status_group",
|
||||||
|
"attempt_count_bucket",
|
||||||
|
"duration_bucket",
|
||||||
|
"component_boundary",
|
||||||
|
"mismatch_kind",
|
||||||
|
"operation",
|
||||||
|
"reason",
|
||||||
|
"queue_size_bucket",
|
||||||
|
] as const);
|
||||||
|
export type DiagnosticContextKey =
|
||||||
|
(typeof DIAGNOSTIC_CONTEXT_ALLOWLIST)[number];
|
||||||
|
export type DiagnosticContext = Readonly<
|
||||||
|
Partial<Record<DiagnosticContextKey, string | number | boolean>>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type DiagnosticRecordInput = Readonly<{
|
||||||
|
level: DiagnosticLevel;
|
||||||
|
eventId: DiagnosticEventId;
|
||||||
|
context?: Readonly<Record<string, unknown>>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type DiagnosticRecord = Readonly<{
|
||||||
|
level: DiagnosticLevel;
|
||||||
|
eventId: DiagnosticEventId;
|
||||||
|
timestamp: string;
|
||||||
|
context: DiagnosticContext;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
const SAFE_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,63}$/;
|
||||||
|
|
||||||
|
function projectDiagnosticRecordUnsafe(
|
||||||
|
input: DiagnosticRecordInput,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
):
|
||||||
|
| Readonly<{ success: true; record: DiagnosticRecord }>
|
||||||
|
| Readonly<{ success: false; reason: string }> {
|
||||||
|
if (!Object.hasOwn(DIAGNOSTIC_EVENT_REGISTRY, input.eventId)) {
|
||||||
|
return { success: false, reason: "unregistered-event" };
|
||||||
|
}
|
||||||
|
if (!DIAGNOSTIC_LEVELS.includes(input.level)) {
|
||||||
|
return { success: false, reason: "invalid-level" };
|
||||||
|
}
|
||||||
|
const contextEntries = Object.entries(input.context ?? {});
|
||||||
|
if (contextEntries.length > DIAGNOSTIC_CONTEXT_ALLOWLIST.length) {
|
||||||
|
return { success: false, reason: "invalid-context" };
|
||||||
|
}
|
||||||
|
const projected: Partial<
|
||||||
|
Record<DiagnosticContextKey, string | number | boolean>
|
||||||
|
> = {};
|
||||||
|
for (const [key, value] of contextEntries) {
|
||||||
|
if (
|
||||||
|
!DIAGNOSTIC_CONTEXT_ALLOWLIST.includes(key as DiagnosticContextKey)
|
||||||
|
) {
|
||||||
|
return { success: false, reason: "unknown-context" };
|
||||||
|
}
|
||||||
|
if (typeof value === "string") {
|
||||||
|
if (!SAFE_VALUE.test(value)) {
|
||||||
|
return { success: false, reason: "invalid-context" };
|
||||||
|
}
|
||||||
|
projected[key as DiagnosticContextKey] = value;
|
||||||
|
} else if (typeof value === "number" && Number.isFinite(value)) {
|
||||||
|
projected[key as DiagnosticContextKey] = value;
|
||||||
|
} else if (typeof value === "boolean") {
|
||||||
|
projected[key as DiagnosticContextKey] = value;
|
||||||
|
} else {
|
||||||
|
return { success: false, reason: "invalid-context" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let timestamp: string;
|
||||||
|
try {
|
||||||
|
timestamp = new Date(now()).toISOString();
|
||||||
|
} catch {
|
||||||
|
timestamp = new Date(0).toISOString();
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
record: Object.freeze({
|
||||||
|
level: input.level,
|
||||||
|
eventId: input.eventId,
|
||||||
|
timestamp,
|
||||||
|
context: Object.freeze(projected),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectDiagnosticRecord(
|
||||||
|
input: DiagnosticRecordInput,
|
||||||
|
now: () => number = Date.now,
|
||||||
|
): ReturnType<typeof projectDiagnosticRecordUnsafe> {
|
||||||
|
try {
|
||||||
|
return projectDiagnosticRecordUnsafe(input, now);
|
||||||
|
} catch {
|
||||||
|
return { success: false, reason: "serialization-failure" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function safeErrorKind(error: unknown): string {
|
||||||
|
try {
|
||||||
|
if (error && typeof error === "object") {
|
||||||
|
const record = error as Readonly<Record<string, unknown>>;
|
||||||
|
if (
|
||||||
|
typeof record.kind === "string" &&
|
||||||
|
/^[A-Z][A-Z0-9_]{0,63}$/.test(record.kind)
|
||||||
|
) {
|
||||||
|
return record.kind;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof record.name === "string" &&
|
||||||
|
/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(record.name)
|
||||||
|
) {
|
||||||
|
const normalized = record.name
|
||||||
|
.replace(/([a-z0-9])([A-Z])/g, "$1_$2")
|
||||||
|
.toUpperCase();
|
||||||
|
return /^[A-Z][A-Z0-9_]{0,63}$/.test(normalized)
|
||||||
|
? normalized
|
||||||
|
: "UNKNOWN_FAILURE";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return "UNKNOWN_FAILURE";
|
||||||
|
}
|
||||||
|
return "UNKNOWN_FAILURE";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function statusGroup(status: number | undefined): string {
|
||||||
|
return typeof status === "number" && Number.isFinite(status)
|
||||||
|
? `${Math.max(0, Math.min(9, Math.floor(status / 100)))}xx`
|
||||||
|
: "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function attemptBucket(attemptCount: number): string {
|
||||||
|
if (attemptCount <= 1) return "1";
|
||||||
|
if (attemptCount === 2) return "2";
|
||||||
|
if (attemptCount <= 4) return "3-4";
|
||||||
|
return "5+";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function durationBucket(durationMs: number): string {
|
||||||
|
if (!Number.isFinite(durationMs) || durationMs < 0) return "unknown";
|
||||||
|
if (durationMs < 100) return "lt100ms";
|
||||||
|
if (durationMs < 500) return "100-499ms";
|
||||||
|
if (durationMs < 2_000) return "500-1999ms";
|
||||||
|
return "gte2000ms";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function queueSizeBucket(size: number): string {
|
||||||
|
if (size <= 0) return "0";
|
||||||
|
if (size <= 10) return "1-10";
|
||||||
|
if (size <= 50) return "11-50";
|
||||||
|
return "51+";
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
/**
|
||||||
|
* @typedef {{
|
||||||
|
* schemaId: string,
|
||||||
|
* boundary: "route-params" | "route-search" |
|
||||||
|
* "route-search-api-request" | "api-request" | "api-response",
|
||||||
|
* owner: string,
|
||||||
|
* runtime: "zod"
|
||||||
|
* }} SchemaDefinition
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const PLATFORM_SCHEMA_REGISTRY =
|
||||||
|
/** @type {Readonly<Record<string, Readonly<SchemaDefinition>>>} */ (
|
||||||
|
Object.freeze({
|
||||||
|
none: Object.freeze({
|
||||||
|
schemaId: "none",
|
||||||
|
boundary: "route-params",
|
||||||
|
owner: "feature-frontend-routing-release-recovery-runtime",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
NotFoundSplat: Object.freeze({
|
||||||
|
schemaId: "NotFoundSplat",
|
||||||
|
boundary: "route-params",
|
||||||
|
owner: "feature-frontend-routing-release-recovery-runtime",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
);
|
||||||
Vendored
+36
@@ -0,0 +1,36 @@
|
|||||||
|
export type TelemetryEventName =
|
||||||
|
| "app.boot.failed"
|
||||||
|
| "api.request.failed"
|
||||||
|
| "ui.render.failed"
|
||||||
|
| "release.mismatch.detected"
|
||||||
|
| "telemetry.delivery.dropped";
|
||||||
|
|
||||||
|
export type TelemetryDefinition = Readonly<{
|
||||||
|
eventName: TelemetryEventName;
|
||||||
|
trigger: string;
|
||||||
|
requiredAttributes: readonly string[];
|
||||||
|
optionalAttributes: readonly string[];
|
||||||
|
forbiddenAttributes: readonly string[];
|
||||||
|
sampling: string;
|
||||||
|
delivery: "best-effort";
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type TelemetryEvent = Readonly<{
|
||||||
|
eventName: TelemetryEventName;
|
||||||
|
timestamp: string;
|
||||||
|
attributes: Readonly<Record<string, unknown>>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const TELEMETRY_ATTRIBUTE_ALLOWLIST: readonly string[];
|
||||||
|
export const TELEMETRY_FORBIDDEN_ATTRIBUTES: readonly string[];
|
||||||
|
export const TELEMETRY_REGISTRY: Readonly<
|
||||||
|
Record<TelemetryEventName, TelemetryDefinition>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export function projectTelemetryEvent(
|
||||||
|
eventName: string,
|
||||||
|
attributes: Record<string, unknown>,
|
||||||
|
now?: () => number,
|
||||||
|
):
|
||||||
|
| Readonly<{ success: true; event: TelemetryEvent }>
|
||||||
|
| Readonly<{ success: false; reason: string }>;
|
||||||
@@ -81,7 +81,7 @@ export const TELEMETRY_REGISTRY = Object.freeze({
|
|||||||
"http_status_group",
|
"http_status_group",
|
||||||
"attempt_count_bucket",
|
"attempt_count_bucket",
|
||||||
"route_id",
|
"route_id",
|
||||||
]),
|
], ["operation_id", "duration_bucket"]),
|
||||||
"ui.render.failed": event("ui.render.failed", "React boundary catch", [
|
"ui.render.failed": event("ui.render.failed", "React boundary catch", [
|
||||||
"route_id",
|
"route_id",
|
||||||
"build_id",
|
"build_id",
|
||||||
@@ -101,11 +101,44 @@ export const TELEMETRY_REGISTRY = Object.freeze({
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const SAFE_IDENTIFIER = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,63}$/;
|
||||||
|
const ATTRIBUTE_VALUE_POLICIES =
|
||||||
|
/** @type {Readonly<Record<string, (value: string) => boolean>>} */ (
|
||||||
|
Object.freeze({
|
||||||
|
route_id: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
operation_id: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
error_kind: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
http_status_group: (value) => /^(?:[1-5]xx|none)$/.test(value),
|
||||||
|
attempt_count_bucket: (value) => /^(?:1|2|3|3-4|5\+)$/.test(value),
|
||||||
|
duration_bucket: (value) =>
|
||||||
|
/^(?:lt100ms|100-499ms|500-1999ms|gte2000ms|unknown)$/.test(
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
component_boundary: (value) =>
|
||||||
|
/^(?:route|feature|boot)$/.test(value),
|
||||||
|
mismatch_kind: (value) => /^[A-Z][A-Z0-9_]{0,63}$/.test(value),
|
||||||
|
reason: (value) =>
|
||||||
|
/^(?:queue-full|sink-failure|invalid-event|invalid-context|serialization-failure)$/.test(
|
||||||
|
value,
|
||||||
|
),
|
||||||
|
queue_size_bucket: (value) =>
|
||||||
|
/^(?:0|1-10|11-50|51\+)$/.test(value),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
/** @param {string} key @param {unknown} value */
|
||||||
|
function validAttributeValue(key, value) {
|
||||||
|
if (typeof value !== "string") return false;
|
||||||
|
const policy = ATTRIBUTE_VALUE_POLICIES[key];
|
||||||
|
return policy ? policy(value) : SAFE_IDENTIFIER.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} eventName
|
* @param {string} eventName
|
||||||
* @param {Record<string, unknown>} attributes
|
* @param {Record<string, unknown>} attributes
|
||||||
|
* @param {() => number} [now]
|
||||||
*/
|
*/
|
||||||
export function projectTelemetryEvent(eventName, attributes) {
|
function projectTelemetryEventUnsafe(eventName, attributes, now = Date.now) {
|
||||||
const registry =
|
const registry =
|
||||||
/** @type {Record<string, (typeof TELEMETRY_REGISTRY)[keyof typeof TELEMETRY_REGISTRY]>} */ (
|
/** @type {Record<string, (typeof TELEMETRY_REGISTRY)[keyof typeof TELEMETRY_REGISTRY]>} */ (
|
||||||
TELEMETRY_REGISTRY
|
TELEMETRY_REGISTRY
|
||||||
@@ -118,13 +151,47 @@ export function projectTelemetryEvent(eventName, attributes) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const attributeKeys = Object.keys(attributes);
|
||||||
|
if (
|
||||||
|
attributeKeys.length >
|
||||||
|
TELEMETRY_ATTRIBUTE_ALLOWLIST.length +
|
||||||
|
TELEMETRY_FORBIDDEN_ATTRIBUTES.length
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "invalid-attribute-value",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const unknown = attributeKeys.filter(
|
||||||
|
(key) =>
|
||||||
|
!TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
||||||
|
!TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key),
|
||||||
|
);
|
||||||
|
if (unknown.length > 0) {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "unknown-attributes",
|
||||||
|
};
|
||||||
|
}
|
||||||
const projected = Object.fromEntries(
|
const projected = Object.fromEntries(
|
||||||
Object.entries(attributes).filter(
|
Object.entries(attributes).filter(
|
||||||
([key]) =>
|
([key, value]) =>
|
||||||
TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
||||||
!TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key),
|
!TELEMETRY_FORBIDDEN_ATTRIBUTES.includes(key) &&
|
||||||
|
validAttributeValue(key, value),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
const invalid = Object.entries(attributes).filter(
|
||||||
|
([key, value]) =>
|
||||||
|
TELEMETRY_ATTRIBUTE_ALLOWLIST.includes(key) &&
|
||||||
|
!validAttributeValue(key, value),
|
||||||
|
);
|
||||||
|
if (invalid.length > 0) {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "invalid-attribute-value",
|
||||||
|
};
|
||||||
|
}
|
||||||
const missing = definition.requiredAttributes.filter(
|
const missing = definition.requiredAttributes.filter(
|
||||||
(key) => projected[key] === undefined,
|
(key) => projected[key] === undefined,
|
||||||
);
|
);
|
||||||
@@ -135,11 +202,34 @@ export function projectTelemetryEvent(eventName, attributes) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let timestamp;
|
||||||
|
try {
|
||||||
|
timestamp = new Date(now()).toISOString();
|
||||||
|
} catch {
|
||||||
|
timestamp = new Date(0).toISOString();
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
success: /** @type {true} */ (true),
|
success: /** @type {true} */ (true),
|
||||||
event: Object.freeze({
|
event: Object.freeze({
|
||||||
eventName,
|
eventName,
|
||||||
|
timestamp,
|
||||||
attributes: Object.freeze(projected),
|
attributes: Object.freeze(projected),
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} eventName
|
||||||
|
* @param {Record<string, unknown>} attributes
|
||||||
|
* @param {() => number} [now]
|
||||||
|
*/
|
||||||
|
export function projectTelemetryEvent(eventName, attributes, now = Date.now) {
|
||||||
|
try {
|
||||||
|
return projectTelemetryEventUnsafe(eventName, attributes, now);
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
success: /** @type {false} */ (false),
|
||||||
|
reason: "serialization-failure",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.js";
|
import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.js";
|
||||||
import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.js";
|
import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.js";
|
||||||
|
import { PLATFORM_SCHEMA_REGISTRY } from "../contracts/schema-registry.js";
|
||||||
import { REFERENCE_FEATURE_CONTRACT } from "./reference-feature/contracts/reference-feature-contract.js";
|
import { REFERENCE_FEATURE_CONTRACT } from "./reference-feature/contracts/reference-feature-contract.js";
|
||||||
|
|
||||||
export const INSTALLED_FEATURE_CONTRACTS = Object.freeze([
|
export const INSTALLED_FEATURE_CONTRACTS = Object.freeze([
|
||||||
@@ -20,6 +21,10 @@ export const API_OPERATIONS = Object.freeze({
|
|||||||
export const QUERY_REGISTRY = Object.freeze({
|
export const QUERY_REGISTRY = Object.freeze({
|
||||||
...REFERENCE_FEATURE_CONTRACT.queryRegistry,
|
...REFERENCE_FEATURE_CONTRACT.queryRegistry,
|
||||||
});
|
});
|
||||||
|
export const SCHEMA_REGISTRY = Object.freeze({
|
||||||
|
...PLATFORM_SCHEMA_REGISTRY,
|
||||||
|
...REFERENCE_FEATURE_CONTRACT.schemas,
|
||||||
|
});
|
||||||
|
|
||||||
export const NAVIGATION_ROUTES = Object.freeze(
|
export const NAVIGATION_ROUTES = Object.freeze(
|
||||||
Object.values(ROUTE_REGISTRY)
|
Object.values(ROUTE_REGISTRY)
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { REFERENCE_MESSAGE_CATALOGS } from "./reference-feature/contracts/reference-message-catalog.js";
|
||||||
|
|
||||||
|
export const INSTALLED_MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": Object.freeze({
|
||||||
|
...REFERENCE_MESSAGE_CATALOGS["ko-KR"],
|
||||||
|
}),
|
||||||
|
"en-US": Object.freeze({
|
||||||
|
...REFERENCE_MESSAGE_CATALOGS["en-US"],
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -14,6 +14,44 @@ export const referenceQueryKeys = Object.freeze({
|
|||||||
|
|
||||||
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
|
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
|
||||||
featureId: REFERENCE_FEATURE_ID,
|
featureId: REFERENCE_FEATURE_ID,
|
||||||
|
schemas: Object.freeze({
|
||||||
|
ReferenceResourceParams: Object.freeze({
|
||||||
|
schemaId: "ReferenceResourceParams",
|
||||||
|
boundary: "route-params",
|
||||||
|
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
ReferenceResourceListQuery: Object.freeze({
|
||||||
|
schemaId: "ReferenceResourceListQuery",
|
||||||
|
boundary: "route-search-api-request",
|
||||||
|
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
CreateReferenceResourceCommand: Object.freeze({
|
||||||
|
schemaId: "CreateReferenceResourceCommand",
|
||||||
|
boundary: "api-request",
|
||||||
|
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
NoRequest: Object.freeze({
|
||||||
|
schemaId: "NoRequest",
|
||||||
|
boundary: "api-request",
|
||||||
|
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
ReferenceResourceListPayload: Object.freeze({
|
||||||
|
schemaId: "ReferenceResourceListPayload",
|
||||||
|
boundary: "api-response",
|
||||||
|
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
ReferenceResourcePayload: Object.freeze({
|
||||||
|
schemaId: "ReferenceResourcePayload",
|
||||||
|
boundary: "api-response",
|
||||||
|
owner: "feature-frontend-reference-feature-vertical-slice",
|
||||||
|
runtime: "zod",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
routes: Object.freeze({
|
routes: Object.freeze({
|
||||||
REFERENCE_RESOURCE_LIST: Object.freeze({
|
REFERENCE_RESOURCE_LIST: Object.freeze({
|
||||||
routeId: "REFERENCE_RESOURCE_LIST",
|
routeId: "REFERENCE_RESOURCE_LIST",
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
export type ReferenceResourceView = Readonly<{
|
export type ReferenceResourceView = Readonly<{
|
||||||
resourceId: string;
|
resourceId: string;
|
||||||
title: string;
|
title: string;
|
||||||
createdAtLabel: string | null;
|
createdAt: string | null;
|
||||||
optimistic?: boolean;
|
optimistic?: boolean;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
@@ -44,14 +44,10 @@ export function mapReferenceOperation(
|
|||||||
|
|
||||||
export function toReferenceView(
|
export function toReferenceView(
|
||||||
resource: ReferenceResource,
|
resource: ReferenceResource,
|
||||||
formatDate: (value: Date) => string = (value) =>
|
|
||||||
new Intl.DateTimeFormat("ko-KR").format(value),
|
|
||||||
): ReferenceResourceView {
|
): ReferenceResourceView {
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
resourceId: resource.id,
|
resourceId: resource.id,
|
||||||
title: resource.displayName,
|
title: resource.displayName,
|
||||||
createdAtLabel: resource.createdAt
|
createdAt: resource.createdAt,
|
||||||
? formatDate(new Date(resource.createdAt))
|
|
||||||
: null,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({
|
||||||
|
"ko-KR": Object.freeze({
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
|
||||||
|
}),
|
||||||
|
"en-US": Object.freeze({
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
|
||||||
|
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
|
||||||
|
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
|
||||||
|
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
|
||||||
|
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -39,6 +39,7 @@ const payloadSchemas = {
|
|||||||
|
|
||||||
const requestSchemas = {
|
const requestSchemas = {
|
||||||
ReferenceResourceListQuery: referenceResourceListQuerySchema,
|
ReferenceResourceListQuery: referenceResourceListQuerySchema,
|
||||||
|
NoRequest: z.object({}).strict(),
|
||||||
CreateReferenceResourceCommand: z
|
CreateReferenceResourceCommand: z
|
||||||
.object({
|
.object({
|
||||||
name: z.string().trim().min(1).max(120),
|
name: z.string().trim().min(1).max(120),
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
|
|
||||||
import { AsyncSurface } from "../../../presentation/components/async-surface.jsx";
|
import {
|
||||||
import { DetailPage } from "../../../presentation/templates/index.js";
|
AsyncSurface,
|
||||||
|
DetailPage,
|
||||||
|
} from "../../../presentation/design-system/index.js";
|
||||||
import { useRouteInput } from "../../../presentation/routes/app-router.js";
|
import { useRouteInput } from "../../../presentation/routes/app-router.js";
|
||||||
|
import { useLocale } from "../../../presentation/i18n/index.js";
|
||||||
import { useReferenceDetail } from "./use-reference-feature.js";
|
import { useReferenceDetail } from "./use-reference-feature.js";
|
||||||
|
|
||||||
export default function ReferenceResourceDetailPage() {
|
export default function ReferenceResourceDetailPage() {
|
||||||
|
const { date, message } = useLocale();
|
||||||
const route = useRouteInput();
|
const route = useRouteInput();
|
||||||
const resourceId = String(route.params.resourceId);
|
const resourceId = String(route.params.resourceId);
|
||||||
const { query } = useReferenceDetail(resourceId);
|
const { query } = useReferenceDetail(resourceId);
|
||||||
@@ -28,7 +32,11 @@ export default function ReferenceResourceDetailPage() {
|
|||||||
<dt>Resource ID</dt>
|
<dt>Resource ID</dt>
|
||||||
<dd>{resource.resourceId}</dd>
|
<dd>{resource.resourceId}</dd>
|
||||||
<dt>Created</dt>
|
<dt>Created</dt>
|
||||||
<dd>{resource.createdAtLabel ?? "표시 정보 없음"}</dd>
|
<dd>
|
||||||
|
{resource.createdAt
|
||||||
|
? date(new Date(resource.createdAt))
|
||||||
|
: message("common.noDisplayValue")}
|
||||||
|
</dd>
|
||||||
</dl>
|
</dl>
|
||||||
) : (
|
) : (
|
||||||
<p>요약 정보를 준비하고 있습니다.</p>
|
<p>요약 정보를 준비하고 있습니다.</p>
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
import { useCallback } from "react";
|
import { useCallback } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
import { Button } from "../../../presentation/components/ui/button.jsx";
|
|
||||||
import {
|
import {
|
||||||
|
Button,
|
||||||
DirtyNavigationDialog,
|
DirtyNavigationDialog,
|
||||||
ErrorSummary,
|
ErrorSummary,
|
||||||
Form,
|
Form,
|
||||||
FormActions,
|
FormActions,
|
||||||
|
FormPage,
|
||||||
FormField,
|
FormField,
|
||||||
useAppForm,
|
useAppForm,
|
||||||
useDirtyNavigationGuard,
|
useDirtyNavigationGuard,
|
||||||
} from "../../../presentation/forms/index.js";
|
} from "../../../presentation/design-system/index.js";
|
||||||
import { FormPage } from "../../../presentation/templates/index.js";
|
|
||||||
import {
|
import {
|
||||||
REFERENCE_FORM_DEFAULTS,
|
REFERENCE_FORM_DEFAULTS,
|
||||||
referenceResourceFormSchema,
|
referenceResourceFormSchema,
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { Link, useNavigate } from "react-router-dom";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
import { AsyncSurface } from "../../../presentation/components/async-surface.jsx";
|
import {
|
||||||
import { Button } from "../../../presentation/components/ui/button.jsx";
|
AsyncSurface,
|
||||||
import { CollectionPage } from "../../../presentation/templates/index.js";
|
Button,
|
||||||
|
CollectionPage,
|
||||||
|
} from "../../../presentation/design-system/index.js";
|
||||||
import { useReferenceFeature } from "./use-reference-feature.js";
|
import { useReferenceFeature } from "./use-reference-feature.js";
|
||||||
|
|
||||||
export default function ReferenceResourcePage() {
|
export default function ReferenceResourcePage() {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
import { StatusPage } from "../../../presentation/templates/index.js";
|
import { StatusPage } from "../../../presentation/design-system/index.js";
|
||||||
|
|
||||||
export default function ReferenceResourceStatusPage() {
|
export default function ReferenceResourceStatusPage() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ export function useReferenceFeature() {
|
|||||||
{
|
{
|
||||||
resourceId: `optimistic:${command.name}`,
|
resourceId: `optimistic:${command.name}`,
|
||||||
title: command.name,
|
title: command.name,
|
||||||
createdAtLabel: null,
|
createdAt: null,
|
||||||
optimistic: true,
|
optimistic: true,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { formatMessage } from "../i18n/index.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{
|
* @param {{
|
||||||
* kind?: string,
|
* kind?: string,
|
||||||
@@ -18,32 +20,36 @@ export function BootErrorShell({
|
|||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<main role="alert">
|
<main role="alert">
|
||||||
<h1>애플리케이션을 시작할 수 없습니다.</h1>
|
<h1>{formatMessage("ko-KR", "boot.failure.title")}</h1>
|
||||||
<dl>
|
<dl>
|
||||||
<dt>오류</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.error")}</dt>
|
||||||
<dd>{kind}</dd>
|
<dd>{kind}</dd>
|
||||||
<dt>코드</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.code")}</dt>
|
||||||
<dd>{code}</dd>
|
<dd>{code}</dd>
|
||||||
{buildId && (
|
{buildId && (
|
||||||
<>
|
<>
|
||||||
<dt>빌드</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.build")}</dt>
|
||||||
<dd>{buildId}</dd>
|
<dd>{buildId}</dd>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{configSchemaVersion && (
|
{configSchemaVersion && (
|
||||||
<>
|
<>
|
||||||
<dt>설정 스키마</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.configSchema")}</dt>
|
||||||
<dd>{configSchemaVersion}</dd>
|
<dd>{configSchemaVersion}</dd>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{releaseId && (
|
{releaseId && (
|
||||||
<>
|
<>
|
||||||
<dt>릴리스</dt>
|
<dt>{formatMessage("ko-KR", "boot.field.release")}</dt>
|
||||||
<dd>{releaseId}</dd>
|
<dd>{releaseId}</dd>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</dl>
|
</dl>
|
||||||
<p>지원 참조: {supportReference}</p>
|
<p>
|
||||||
|
{formatMessage("ko-KR", "boot.supportReference", {
|
||||||
|
reference: supportReference,
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
type ErrorInfo,
|
type ErrorInfo,
|
||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
type RecoveryResult =
|
type RecoveryResult =
|
||||||
| Readonly<{ action: "reload-once"; releasePair: string }>
|
| Readonly<{ action: "reload-once"; releasePair: string }>
|
||||||
@@ -71,27 +72,44 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
|
|||||||
const { error, recovery, reason } = this.state;
|
const { error, recovery, reason } = this.state;
|
||||||
if (error && !isChunkLoadFailure(error)) throw error;
|
if (error && !isChunkLoadFailure(error)) throw error;
|
||||||
if (error && recovery === "checking") {
|
if (error && recovery === "checking") {
|
||||||
return (
|
return <ChunkRecoverySurface recovery="checking" />;
|
||||||
<section className="ui-page" aria-live="polite" aria-busy="true">
|
|
||||||
새 릴리스 정보를 확인하고 있습니다.
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (error && recovery === "reload-requested") {
|
if (error && recovery === "reload-requested") {
|
||||||
return (
|
return <ChunkRecoverySurface recovery="reload-requested" />;
|
||||||
<section className="ui-page" aria-live="polite">
|
|
||||||
새 버전으로 한 번만 전환합니다.
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (error && recovery === "support") {
|
if (error && recovery === "support") {
|
||||||
return (
|
return <ChunkRecoverySurface recovery="support" reason={reason} />;
|
||||||
<section className="ui-page" role="alert" data-recovery-reason={reason}>
|
|
||||||
<h1>화면 자산을 복구하지 못했습니다.</h1>
|
|
||||||
<p>문제가 계속되면 배포 상태와 지원 참조 정보를 확인해 주세요.</p>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return this.props.children;
|
return this.props.children;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ChunkRecoverySurface({
|
||||||
|
recovery,
|
||||||
|
reason,
|
||||||
|
}: Readonly<{
|
||||||
|
recovery: Exclude<State["recovery"], "idle">;
|
||||||
|
reason?: string;
|
||||||
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
if (recovery === "checking") {
|
||||||
|
return (
|
||||||
|
<section className="ui-page" aria-live="polite" aria-busy="true">
|
||||||
|
{message("chunk.checking")}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (recovery === "reload-requested") {
|
||||||
|
return (
|
||||||
|
<section className="ui-page" aria-live="polite">
|
||||||
|
{message("chunk.reloadOnce")}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<section className="ui-page" role="alert" data-recovery-reason={reason}>
|
||||||
|
<h1>{message("chunk.failure.title")}</h1>
|
||||||
|
<p>{message("chunk.failure.description")}</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Component } from "react";
|
import { Component } from "react";
|
||||||
|
import { formatMessage } from "../i18n/index.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @typedef {{
|
* @typedef {{
|
||||||
@@ -57,9 +58,9 @@ export class RenderErrorBoundary extends Component {
|
|||||||
return (
|
return (
|
||||||
this.props.fallback ?? (
|
this.props.fallback ?? (
|
||||||
<section role="alert">
|
<section role="alert">
|
||||||
<p>error.render_failure</p>
|
<p>{formatMessage("ko-KR", "error.render_failure")}</p>
|
||||||
<button type="button" onClick={this.reset}>
|
<button type="button" onClick={this.reset}>
|
||||||
retry
|
{formatMessage("ko-KR", "action.retry")}
|
||||||
</button>
|
</button>
|
||||||
</section>
|
</section>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,19 +2,22 @@ import { useId } from "react";
|
|||||||
|
|
||||||
import { errorMessage } from "./error-copy.js";
|
import { errorMessage } from "./error-copy.js";
|
||||||
import { Button } from "./ui/button.jsx";
|
import { Button } from "./ui/button.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
/** @param {{ label?: string }} props */
|
/** @param {{ label?: string }} props */
|
||||||
export function LoadingSurface({ label = "불러오는 중" }) {
|
export function LoadingSurface({ label }) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
const accessibleLabel = label ?? message("async.loading");
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className="state-surface state-surface--loading"
|
className="state-surface state-surface--loading"
|
||||||
aria-busy="true"
|
aria-busy="true"
|
||||||
aria-label={label}
|
aria-label={accessibleLabel}
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
aria-atomic="true"
|
aria-atomic="true"
|
||||||
>
|
>
|
||||||
<div className="ui-skeleton" aria-hidden="true" />
|
<div className="ui-skeleton" aria-hidden="true" />
|
||||||
<span className="visually-hidden">{label}</span>
|
<span className="visually-hidden">{accessibleLabel}</span>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -27,13 +30,14 @@ export function LoadingSurface({ label = "불러오는 중" }) {
|
|||||||
* }} props
|
* }} props
|
||||||
*/
|
*/
|
||||||
export function EmptySurface({
|
export function EmptySurface({
|
||||||
title = "표시할 항목이 없습니다.",
|
title,
|
||||||
description,
|
description,
|
||||||
action,
|
action,
|
||||||
}) {
|
}) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<section className="ui-empty state-surface" aria-live="polite">
|
<section className="ui-empty state-surface" aria-live="polite">
|
||||||
<h2>{title}</h2>
|
<h2>{title ?? message("async.empty")}</h2>
|
||||||
{description ? <p>{description}</p> : null}
|
{description ? <p>{description}</p> : null}
|
||||||
{action}
|
{action}
|
||||||
</section>
|
</section>
|
||||||
@@ -49,13 +53,14 @@ export function EmptySurface({
|
|||||||
* }} props
|
* }} props
|
||||||
*/
|
*/
|
||||||
export function TerminalErrorSurface({ userMessageKey, action, onAction }) {
|
export function TerminalErrorSurface({ userMessageKey, action, onAction }) {
|
||||||
|
const { locale, message } = useLocale();
|
||||||
const messageId = useId();
|
const messageId = useId();
|
||||||
const actionLabels = Object.freeze({
|
const actionLabels = Object.freeze({
|
||||||
retry: "다시 시도",
|
retry: message("action.retry"),
|
||||||
reauth: "로그인",
|
reauth: message("action.reauth"),
|
||||||
navigate: "안전한 화면으로 이동",
|
navigate: message("action.navigateSafe"),
|
||||||
"reload-once": "한 번 새로고침",
|
"reload-once": message("action.reloadOnce"),
|
||||||
"contact-support": "지원 정보 확인",
|
"contact-support": message("action.contactSupport"),
|
||||||
});
|
});
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
@@ -64,7 +69,7 @@ export function TerminalErrorSurface({ userMessageKey, action, onAction }) {
|
|||||||
aria-labelledby={messageId}
|
aria-labelledby={messageId}
|
||||||
data-message-key={userMessageKey}
|
data-message-key={userMessageKey}
|
||||||
>
|
>
|
||||||
<h2 id={messageId}>{errorMessage(userMessageKey)}</h2>
|
<h2 id={messageId}>{errorMessage(userMessageKey, locale)}</h2>
|
||||||
{action !== "none" && onAction && (
|
{action !== "none" && onAction && (
|
||||||
<Button onClick={onAction}>{actionLabels[action]}</Button>
|
<Button onClick={onAction}>{actionLabels[action]}</Button>
|
||||||
)}
|
)}
|
||||||
@@ -88,6 +93,7 @@ export function AsyncSurface({
|
|||||||
onRetry,
|
onRetry,
|
||||||
onResolveConflict,
|
onResolveConflict,
|
||||||
}) {
|
}) {
|
||||||
|
const { message } = useLocale();
|
||||||
if (state.base === "initial-loading") return <LoadingSurface />;
|
if (state.base === "initial-loading") return <LoadingSurface />;
|
||||||
if (state.base === "empty") return <EmptySurface />;
|
if (state.base === "empty") return <EmptySurface />;
|
||||||
if (state.base === "terminal-error" && state.failure) {
|
if (state.base === "terminal-error" && state.failure) {
|
||||||
@@ -104,12 +110,24 @@ export function AsyncSurface({
|
|||||||
<section aria-busy={state.overlay.refreshing || state.overlay.mutationPending}>
|
<section aria-busy={state.overlay.refreshing || state.overlay.mutationPending}>
|
||||||
{state.indicator ? (
|
{state.indicator ? (
|
||||||
<div role="status" aria-live="polite">
|
<div role="status" aria-live="polite">
|
||||||
<span>{state.indicator}</span>
|
<span>
|
||||||
|
{message(
|
||||||
|
state.indicator === "stale-degraded"
|
||||||
|
? "async.staleDegraded"
|
||||||
|
: state.indicator === "mutation-conflict"
|
||||||
|
? "async.mutationConflict"
|
||||||
|
: state.indicator === "mutation-pending"
|
||||||
|
? "async.mutationPending"
|
||||||
|
: "async.refreshing",
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
{state.indicator === "stale-degraded" && onRetry ? (
|
{state.indicator === "stale-degraded" && onRetry ? (
|
||||||
<Button onClick={onRetry}>다시 시도</Button>
|
<Button onClick={onRetry}>{message("action.retry")}</Button>
|
||||||
) : null}
|
) : null}
|
||||||
{state.indicator === "mutation-conflict" && onResolveConflict ? (
|
{state.indicator === "mutation-conflict" && onResolveConflict ? (
|
||||||
<Button onClick={onResolveConflict}>충돌 해결</Button>
|
<Button onClick={onResolveConflict}>
|
||||||
|
{message("action.resolveConflict")}
|
||||||
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -1,26 +1,6 @@
|
|||||||
const ERROR_MESSAGES = Object.freeze({
|
import { resolveMessage } from "../i18n/index.js";
|
||||||
"error.network_unreachable": "네트워크에 연결할 수 없습니다.",
|
|
||||||
"error.request_timeout": "요청 시간이 초과되었습니다.",
|
|
||||||
"error.auth_required": "계속하려면 로그인이 필요합니다.",
|
|
||||||
"error.auth_integration_failure": "로그인 연동을 사용할 수 없습니다.",
|
|
||||||
"error.forbidden": "이 작업을 수행할 권한이 없습니다.",
|
|
||||||
"error.not_found": "요청한 항목을 찾을 수 없습니다.",
|
|
||||||
"error.rate_limited": "요청이 많습니다. 잠시 후 다시 시도해 주세요.",
|
|
||||||
"error.server_failure": "요청을 완료하지 못했습니다.",
|
|
||||||
"error.chunk_load_failure": "새 화면 파일을 불러오지 못했습니다.",
|
|
||||||
"error.build_mismatch": "현재 화면과 활성 빌드가 일치하지 않습니다.",
|
|
||||||
"error.config_mismatch": "런타임 설정 버전이 현재 화면과 일치하지 않습니다.",
|
|
||||||
"error.api_contract_mismatch": "API 계약 버전이 현재 화면과 일치하지 않습니다.",
|
|
||||||
"error.release_mismatch": "현재 화면과 활성 릴리스가 일치하지 않습니다.",
|
|
||||||
"error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.",
|
|
||||||
"error.render_failure": "화면을 표시하지 못했습니다.",
|
|
||||||
"error.unknown_failure": "예상하지 못한 문제가 발생했습니다.",
|
|
||||||
});
|
|
||||||
|
|
||||||
/** @param {string} messageKey */
|
/** @param {string} messageKey @param {string} [locale] */
|
||||||
export function errorMessage(messageKey) {
|
export function errorMessage(messageKey, locale = "ko-KR") {
|
||||||
const messages = /** @type {Readonly<Record<string, string>>} */ (
|
return resolveMessage(locale, messageKey);
|
||||||
ERROR_MESSAGES
|
|
||||||
);
|
|
||||||
return messages[messageKey] ?? "요청을 완료하지 못했습니다.";
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Button } from "./ui/button.jsx";
|
import { Button } from "./ui/button.jsx";
|
||||||
|
import { useLocale } from "../i18n/index.js";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {{
|
* @param {{
|
||||||
@@ -30,12 +31,13 @@ function StateSurface({
|
|||||||
|
|
||||||
/** @param {{ onSignIn?: () => void }} props */
|
/** @param {{ onSignIn?: () => void }} props */
|
||||||
export function AuthRequiredSurface({ onSignIn }) {
|
export function AuthRequiredSurface({ onSignIn }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StateSurface
|
<StateSurface
|
||||||
eyebrow="401 · 인증 필요"
|
eyebrow={message("access.auth.eyebrow")}
|
||||||
title="로그인이 필요합니다."
|
title={message("access.auth.title")}
|
||||||
description="세션을 시작한 뒤 이전 작업을 안전하게 계속할 수 있습니다."
|
description={message("access.auth.description")}
|
||||||
actionLabel="로그인 시작"
|
actionLabel={message("action.signIn")}
|
||||||
onAction={onSignIn}
|
onAction={onSignIn}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -43,12 +45,13 @@ export function AuthRequiredSurface({ onSignIn }) {
|
|||||||
|
|
||||||
/** @param {{ onNavigate?: () => void }} props */
|
/** @param {{ onNavigate?: () => void }} props */
|
||||||
export function ForbiddenSurface({ onNavigate }) {
|
export function ForbiddenSurface({ onNavigate }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StateSurface
|
<StateSurface
|
||||||
eyebrow="403 · 권한 없음"
|
eyebrow={message("access.forbidden.eyebrow")}
|
||||||
title="접근할 수 없습니다."
|
title={message("access.forbidden.title")}
|
||||||
description="권한을 확인하거나 접근 가능한 화면으로 이동하세요."
|
description={message("access.forbidden.description")}
|
||||||
actionLabel="안전한 화면으로 이동"
|
actionLabel={message("action.navigateSafe")}
|
||||||
onAction={onNavigate}
|
onAction={onNavigate}
|
||||||
tone="warning"
|
tone="warning"
|
||||||
/>
|
/>
|
||||||
@@ -57,12 +60,13 @@ export function ForbiddenSurface({ onNavigate }) {
|
|||||||
|
|
||||||
/** @param {{ onNavigate?: () => void }} props */
|
/** @param {{ onNavigate?: () => void }} props */
|
||||||
export function NotFoundSurface({ onNavigate }) {
|
export function NotFoundSurface({ onNavigate }) {
|
||||||
|
const { message } = useLocale();
|
||||||
return (
|
return (
|
||||||
<StateSurface
|
<StateSurface
|
||||||
eyebrow="404 · 찾을 수 없음"
|
eyebrow={message("access.notFound.eyebrow")}
|
||||||
title="요청한 화면이 없습니다."
|
title={message("access.notFound.title")}
|
||||||
description="주소를 확인하거나 시작 화면으로 돌아가세요."
|
description={message("access.notFound.description")}
|
||||||
actionLabel="시작 화면으로 이동"
|
actionLabel={message("action.goHome")}
|
||||||
onAction={onNavigate}
|
onAction={onNavigate}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,36 +1 @@
|
|||||||
/**
|
export { Alert } from "../../design-system/primitives/core.js";
|
||||||
* @param {{
|
|
||||||
* title: string,
|
|
||||||
* children?: React.ReactNode,
|
|
||||||
* variant?: "info" | "success" | "warning" | "danger",
|
|
||||||
* onDismiss?: () => void
|
|
||||||
* }} props
|
|
||||||
*/
|
|
||||||
export function Alert({
|
|
||||||
title,
|
|
||||||
children,
|
|
||||||
variant = "info",
|
|
||||||
onDismiss,
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<section
|
|
||||||
className={`ui-alert ui-alert--${variant}`}
|
|
||||||
role={variant === "danger" ? "alert" : "status"}
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<strong>{title}</strong>
|
|
||||||
{children ? <div className="ui-alert__content">{children}</div> : null}
|
|
||||||
</div>
|
|
||||||
{onDismiss ? (
|
|
||||||
<button
|
|
||||||
className="ui-alert__dismiss"
|
|
||||||
type="button"
|
|
||||||
aria-label={`${title} 알림 닫기`}
|
|
||||||
onClick={onDismiss}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
) : null}
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,9 +1 @@
|
|||||||
/**
|
export { Badge } from "../../design-system/primitives/core.js";
|
||||||
* @param {{
|
|
||||||
* children: React.ReactNode,
|
|
||||||
* variant?: "neutral" | "info" | "success" | "warning" | "danger"
|
|
||||||
* }} props
|
|
||||||
*/
|
|
||||||
export function Badge({ children, variant = "neutral" }) {
|
|
||||||
return <span className={`ui-badge ui-badge--${variant}`}>{children}</span>;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,24 +1 @@
|
|||||||
/**
|
export { Button } from "../../design-system/primitives/core.js";
|
||||||
* @param {React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
|
||||||
* variant?: "primary" | "secondary" | "danger" | "ghost",
|
|
||||||
* size?: "default" | "compact"
|
|
||||||
* }} props
|
|
||||||
*/
|
|
||||||
export function Button({
|
|
||||||
variant = "primary",
|
|
||||||
size = "default",
|
|
||||||
className = "",
|
|
||||||
type = "button",
|
|
||||||
...props
|
|
||||||
}) {
|
|
||||||
const classes = [
|
|
||||||
"ui-button",
|
|
||||||
`ui-button--${variant}`,
|
|
||||||
size === "compact" ? "ui-button--compact" : "",
|
|
||||||
className,
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" ");
|
|
||||||
|
|
||||||
return <button {...props} className={classes} type={type} />;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,28 +1 @@
|
|||||||
import { useId } from "react";
|
export { Card } from "../../design-system/primitives/core.js";
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {{
|
|
||||||
* title: string,
|
|
||||||
* description?: string,
|
|
||||||
* children?: React.ReactNode,
|
|
||||||
* footer?: React.ReactNode,
|
|
||||||
* className?: string
|
|
||||||
* }} props
|
|
||||||
*/
|
|
||||||
export function Card({ title, description, children, footer, className = "" }) {
|
|
||||||
const titleId = useId();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<article
|
|
||||||
className={`ui-card ${className}`.trim()}
|
|
||||||
aria-labelledby={titleId}
|
|
||||||
>
|
|
||||||
<div className="ui-card__header">
|
|
||||||
<h3 id={titleId}>{title}</h3>
|
|
||||||
{description ? <p>{description}</p> : null}
|
|
||||||
</div>
|
|
||||||
{children ? <div className="ui-card__content">{children}</div> : null}
|
|
||||||
{footer ? <footer className="ui-card__footer">{footer}</footer> : null}
|
|
||||||
</article>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,88 +1 @@
|
|||||||
import { useEffect, useId, useRef } from "react";
|
export { Dialog } from "../../design-system/primitives/core.js";
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {{
|
|
||||||
* open: boolean,
|
|
||||||
* onClose: () => void,
|
|
||||||
* title: string,
|
|
||||||
* description?: string,
|
|
||||||
* children?: React.ReactNode,
|
|
||||||
* actions?: React.ReactNode
|
|
||||||
* }} props
|
|
||||||
*/
|
|
||||||
export function Dialog({
|
|
||||||
open,
|
|
||||||
onClose,
|
|
||||||
title,
|
|
||||||
description,
|
|
||||||
children,
|
|
||||||
actions,
|
|
||||||
}) {
|
|
||||||
const dialogRef = useRef(/** @type {HTMLDialogElement | null} */ (null));
|
|
||||||
const previousFocusRef = useRef(/** @type {HTMLElement | null} */ (null));
|
|
||||||
const titleId = useId();
|
|
||||||
const descriptionId = useId();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const dialog = dialogRef.current;
|
|
||||||
if (!dialog) return;
|
|
||||||
|
|
||||||
if (open) {
|
|
||||||
previousFocusRef.current =
|
|
||||||
document.activeElement instanceof HTMLElement
|
|
||||||
? document.activeElement
|
|
||||||
: null;
|
|
||||||
if (!dialog.open) {
|
|
||||||
if (typeof dialog.showModal === "function") dialog.showModal();
|
|
||||||
else dialog.setAttribute("open", "");
|
|
||||||
}
|
|
||||||
const firstFocusable = dialog.querySelector(
|
|
||||||
"[autofocus], button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])",
|
|
||||||
);
|
|
||||||
if (firstFocusable instanceof HTMLElement) firstFocusable.focus();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (dialog.open) {
|
|
||||||
if (typeof dialog.close === "function") dialog.close();
|
|
||||||
else dialog.removeAttribute("open");
|
|
||||||
}
|
|
||||||
previousFocusRef.current?.focus();
|
|
||||||
previousFocusRef.current = null;
|
|
||||||
}, [open]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<dialog
|
|
||||||
className="ui-dialog"
|
|
||||||
ref={dialogRef}
|
|
||||||
aria-labelledby={titleId}
|
|
||||||
aria-describedby={description ? descriptionId : undefined}
|
|
||||||
onCancel={(event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
onClose();
|
|
||||||
}}
|
|
||||||
onClick={(event) => {
|
|
||||||
if (event.target === event.currentTarget) onClose();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<div className="ui-dialog__surface">
|
|
||||||
<header className="ui-dialog__header">
|
|
||||||
<div>
|
|
||||||
<h2 id={titleId}>{title}</h2>
|
|
||||||
{description ? <p id={descriptionId}>{description}</p> : null}
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
className="ui-dialog__close"
|
|
||||||
type="button"
|
|
||||||
aria-label={`${title} 닫기`}
|
|
||||||
onClick={onClose}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
</header>
|
|
||||||
{children ? <div className="ui-dialog__content">{children}</div> : null}
|
|
||||||
{actions ? <footer className="ui-dialog__actions">{actions}</footer> : null}
|
|
||||||
</div>
|
|
||||||
</dialog>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,52 +1 @@
|
|||||||
import { useId } from "react";
|
export { TextField } from "../../design-system/primitives/core.js";
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {Omit<React.InputHTMLAttributes<HTMLInputElement>, "id"> & {
|
|
||||||
* id?: string,
|
|
||||||
* label: string,
|
|
||||||
* description?: string,
|
|
||||||
* error?: string
|
|
||||||
* }} props
|
|
||||||
*/
|
|
||||||
export function TextField({
|
|
||||||
id,
|
|
||||||
label,
|
|
||||||
description,
|
|
||||||
error,
|
|
||||||
className = "",
|
|
||||||
required,
|
|
||||||
...inputProps
|
|
||||||
}) {
|
|
||||||
const generatedId = useId();
|
|
||||||
const inputId = id ?? `field-${generatedId}`;
|
|
||||||
const descriptionId = description ? `${inputId}-description` : undefined;
|
|
||||||
const errorId = error ? `${inputId}-error` : undefined;
|
|
||||||
const describedBy = [descriptionId, errorId].filter(Boolean).join(" ");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={`ui-field ${className}`.trim()}>
|
|
||||||
<label className="ui-field__label" htmlFor={inputId}>
|
|
||||||
{label}
|
|
||||||
{required ? <span aria-hidden="true"> *</span> : null}
|
|
||||||
</label>
|
|
||||||
{description ? (
|
|
||||||
<p className="ui-field__description" id={descriptionId}>
|
|
||||||
{description}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
<input
|
|
||||||
{...inputProps}
|
|
||||||
className="ui-field__input"
|
|
||||||
id={inputId}
|
|
||||||
required={required}
|
|
||||||
aria-describedby={describedBy || undefined}
|
|
||||||
aria-invalid={error ? "true" : undefined}
|
|
||||||
/>
|
|
||||||
{error ? (
|
|
||||||
<p className="ui-field__error" id={errorId}>
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||||
|
import { expect, userEvent, within } from "storybook/test";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Alert,
|
||||||
|
Badge,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Dialog,
|
||||||
|
Menu,
|
||||||
|
ProgressBar,
|
||||||
|
Skeleton,
|
||||||
|
Tabs,
|
||||||
|
TextArea,
|
||||||
|
TextField,
|
||||||
|
} from "./index.js";
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
title: "Platform/Design System",
|
||||||
|
component: Button,
|
||||||
|
tags: ["autodocs"],
|
||||||
|
parameters: {
|
||||||
|
layout: "padded",
|
||||||
|
},
|
||||||
|
} satisfies Meta<typeof Button>;
|
||||||
|
|
||||||
|
export default meta;
|
||||||
|
type Story = StoryObj<typeof meta>;
|
||||||
|
|
||||||
|
export const Primitives: Story = {
|
||||||
|
render: () => (
|
||||||
|
<div className="ui-stack">
|
||||||
|
<Card title="Actions and status">
|
||||||
|
<div className="ui-cluster">
|
||||||
|
<Button>Primary</Button>
|
||||||
|
<Button variant="secondary">Secondary</Button>
|
||||||
|
<Button variant="danger">Danger</Button>
|
||||||
|
<Button pending pendingLabel="Processing">
|
||||||
|
Save
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="ui-cluster">
|
||||||
|
<Badge variant="neutral">Neutral</Badge>
|
||||||
|
<Badge variant="success">Success</Badge>
|
||||||
|
<Badge variant="warning">Warning</Badge>
|
||||||
|
<Badge variant="danger">Danger</Badge>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
<TextField
|
||||||
|
description="A stable accessible description"
|
||||||
|
label="Name"
|
||||||
|
placeholder="Example"
|
||||||
|
/>
|
||||||
|
<TextField error="Enter a name" label="Invalid name" value="" readOnly />
|
||||||
|
<TextArea
|
||||||
|
defaultValue="Long-form content"
|
||||||
|
label="Notes"
|
||||||
|
maxLength={100}
|
||||||
|
/>
|
||||||
|
<Alert title="Platform status" variant="info">
|
||||||
|
The component workshop uses the same tokens and providers as the app.
|
||||||
|
</Alert>
|
||||||
|
<ProgressBar label="Build readiness" value={72} />
|
||||||
|
<Skeleton label="Loading example" />
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
function OverlayExample() {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
return (
|
||||||
|
<div className="ui-stack">
|
||||||
|
<Button onClick={() => setOpen(true)}>Open dialog</Button>
|
||||||
|
<Dialog
|
||||||
|
actions={<Button onClick={() => setOpen(false)}>Confirm</Button>}
|
||||||
|
onClose={() => setOpen(false)}
|
||||||
|
open={open}
|
||||||
|
title="Confirm platform action"
|
||||||
|
>
|
||||||
|
Keyboard dismissal must restore focus to the trigger.
|
||||||
|
</Dialog>
|
||||||
|
<Menu
|
||||||
|
items={[
|
||||||
|
{ id: "first", label: "First action", onSelect() {} },
|
||||||
|
{ id: "second", label: "Second action", onSelect() {} },
|
||||||
|
]}
|
||||||
|
triggerLabel="Open menu"
|
||||||
|
/>
|
||||||
|
<Tabs
|
||||||
|
defaultValue="one"
|
||||||
|
label="Example sections"
|
||||||
|
tabs={[
|
||||||
|
{ id: "one", label: "One", panel: "First panel" },
|
||||||
|
{ id: "two", label: "Two", panel: "Second panel" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const OverlayInteraction: Story = {
|
||||||
|
render: () => <OverlayExample />,
|
||||||
|
play: async ({ canvasElement }) => {
|
||||||
|
const canvas = within(canvasElement);
|
||||||
|
const trigger = canvas.getByRole("button", { name: "Open dialog" });
|
||||||
|
await userEvent.click(trigger);
|
||||||
|
const dialog = within(document.body).getByRole("dialog", {
|
||||||
|
name: "Confirm platform action",
|
||||||
|
});
|
||||||
|
await expect(dialog).toBeVisible();
|
||||||
|
await userEvent.keyboard("{Escape}");
|
||||||
|
await expect(dialog).not.toBeVisible();
|
||||||
|
await expect(trigger).toHaveFocus();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export const LongPseudoLikeContent: Story = {
|
||||||
|
render: () => (
|
||||||
|
<Card title="[!! Ćømƥøñëñţ ţøķëñ åñđ ļøñğ ţëжţ vëŕïƒïćåţïøñ !!]">
|
||||||
|
<p>
|
||||||
|
[!! Ţhïš šţøŕÿ vëŕïƒïëš ţhåţ å ƥŕïmïţïvë ŕëmåïñš ŕëåđåɓļë
|
||||||
|
ïñ å ćømƥåćţ ćøñţåïñëŕ. !!]
|
||||||
|
</p>
|
||||||
|
<Button>[!! Ćøñţïñüë !!]</Button>
|
||||||
|
</Card>
|
||||||
|
),
|
||||||
|
};
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import type { ComponentType, SVGProps } from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
CloseGlyph,
|
||||||
|
ErrorGlyph,
|
||||||
|
InfoGlyph,
|
||||||
|
MenuGlyph,
|
||||||
|
NextGlyph,
|
||||||
|
PreviousGlyph,
|
||||||
|
SearchGlyph,
|
||||||
|
SuccessGlyph,
|
||||||
|
WarningGlyph,
|
||||||
|
} from "./vendors/lucide.js";
|
||||||
|
|
||||||
|
export type SemanticIconProps = Readonly<{
|
||||||
|
label?: string;
|
||||||
|
size?: "small" | "medium" | "large";
|
||||||
|
}>;
|
||||||
|
|
||||||
|
function createSemanticIcon(
|
||||||
|
Glyph: ComponentType<SVGProps<SVGSVGElement>>,
|
||||||
|
) {
|
||||||
|
return function SemanticIcon({
|
||||||
|
label,
|
||||||
|
size = "medium",
|
||||||
|
}: SemanticIconProps) {
|
||||||
|
return (
|
||||||
|
<Glyph
|
||||||
|
aria-hidden={label ? undefined : "true"}
|
||||||
|
aria-label={label}
|
||||||
|
className={`ui-icon ui-icon--${size}`}
|
||||||
|
focusable="false"
|
||||||
|
role={label ? "img" : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MenuIcon = createSemanticIcon(MenuGlyph);
|
||||||
|
export const CloseIcon = createSemanticIcon(CloseGlyph);
|
||||||
|
export const WarningIcon = createSemanticIcon(WarningGlyph);
|
||||||
|
export const SuccessIcon = createSemanticIcon(SuccessGlyph);
|
||||||
|
export const ErrorIcon = createSemanticIcon(ErrorGlyph);
|
||||||
|
export const InfoIcon = createSemanticIcon(InfoGlyph);
|
||||||
|
export const SearchIcon = createSemanticIcon(SearchGlyph);
|
||||||
|
export const PreviousIcon = createSemanticIcon(PreviousGlyph);
|
||||||
|
export const NextIcon = createSemanticIcon(NextGlyph);
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import {
|
||||||
|
AlertTriangle,
|
||||||
|
Check,
|
||||||
|
ChevronLeft,
|
||||||
|
ChevronRight,
|
||||||
|
CircleX,
|
||||||
|
Info,
|
||||||
|
Menu,
|
||||||
|
Search,
|
||||||
|
X,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
export const MenuGlyph = Menu;
|
||||||
|
export const CloseGlyph = X;
|
||||||
|
export const WarningGlyph = AlertTriangle;
|
||||||
|
export const SuccessGlyph = Check;
|
||||||
|
export const ErrorGlyph = CircleX;
|
||||||
|
export const InfoGlyph = Info;
|
||||||
|
export const SearchGlyph = Search;
|
||||||
|
export const PreviousGlyph = ChevronLeft;
|
||||||
|
export const NextGlyph = ChevronRight;
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
export {
|
||||||
|
Alert,
|
||||||
|
Badge,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
Dialog,
|
||||||
|
Field,
|
||||||
|
FocusRing,
|
||||||
|
IconButton,
|
||||||
|
LinkButton,
|
||||||
|
Portal,
|
||||||
|
Spinner,
|
||||||
|
TextField,
|
||||||
|
VisuallyHidden,
|
||||||
|
} from "./primitives/core.js";
|
||||||
|
export type {
|
||||||
|
AlertProps,
|
||||||
|
BadgeProps,
|
||||||
|
ButtonProps,
|
||||||
|
ButtonSize,
|
||||||
|
ButtonVariant,
|
||||||
|
CardProps,
|
||||||
|
DialogProps,
|
||||||
|
IconButtonProps,
|
||||||
|
LinkButtonProps,
|
||||||
|
SpinnerProps,
|
||||||
|
TextFieldProps,
|
||||||
|
} from "./primitives/core.js";
|
||||||
|
export {
|
||||||
|
Checkbox,
|
||||||
|
RadioGroup,
|
||||||
|
SearchField,
|
||||||
|
Select,
|
||||||
|
Switch,
|
||||||
|
TextArea,
|
||||||
|
} from "./primitives/forms.js";
|
||||||
|
export type {
|
||||||
|
CheckboxProps,
|
||||||
|
RadioGroupProps,
|
||||||
|
RadioOption,
|
||||||
|
SearchFieldProps,
|
||||||
|
SelectOption,
|
||||||
|
SelectProps,
|
||||||
|
SwitchProps,
|
||||||
|
TextAreaProps,
|
||||||
|
} from "./primitives/forms.js";
|
||||||
|
export {
|
||||||
|
ProgressBar,
|
||||||
|
Separator,
|
||||||
|
Skeleton,
|
||||||
|
} from "./primitives/feedback.js";
|
||||||
|
export type {
|
||||||
|
ProgressBarProps,
|
||||||
|
SkeletonProps,
|
||||||
|
} from "./primitives/feedback.js";
|
||||||
|
export {
|
||||||
|
ConfirmationDialog,
|
||||||
|
Drawer,
|
||||||
|
Menu,
|
||||||
|
Popover,
|
||||||
|
ToastProvider,
|
||||||
|
Tooltip,
|
||||||
|
useToast,
|
||||||
|
} from "./primitives/overlays.js";
|
||||||
|
export type {
|
||||||
|
DrawerProps,
|
||||||
|
MenuItemDefinition,
|
||||||
|
MenuProps,
|
||||||
|
PopoverProps,
|
||||||
|
TooltipProps,
|
||||||
|
} from "./primitives/overlays.js";
|
||||||
|
export {
|
||||||
|
Breadcrumbs,
|
||||||
|
Pagination,
|
||||||
|
Tabs,
|
||||||
|
} from "./primitives/navigation.js";
|
||||||
|
export type {
|
||||||
|
BreadcrumbItem,
|
||||||
|
TabDefinition,
|
||||||
|
} from "./primitives/navigation.js";
|
||||||
|
export {
|
||||||
|
CloseIcon,
|
||||||
|
ErrorIcon,
|
||||||
|
InfoIcon,
|
||||||
|
MenuIcon,
|
||||||
|
NextIcon,
|
||||||
|
PreviousIcon,
|
||||||
|
SearchIcon,
|
||||||
|
SuccessIcon,
|
||||||
|
WarningIcon,
|
||||||
|
} from "./icons/semantic-icons.js";
|
||||||
|
export type {
|
||||||
|
SemanticIconProps,
|
||||||
|
} from "./icons/semantic-icons.js";
|
||||||
|
export {
|
||||||
|
DESIGN_TOKEN_CONTRACT,
|
||||||
|
REQUIRED_COMPONENT_TOKENS,
|
||||||
|
REQUIRED_PRIMITIVE_TOKENS,
|
||||||
|
REQUIRED_SEMANTIC_TOKENS,
|
||||||
|
} from "./tokens/token-contract.js";
|
||||||
|
export {
|
||||||
|
AccessSurface,
|
||||||
|
DataTable,
|
||||||
|
DisclosureGroup,
|
||||||
|
PaginationBar,
|
||||||
|
SearchFilterToolbar,
|
||||||
|
} from "./patterns/common-patterns.js";
|
||||||
|
export type {
|
||||||
|
AccessSurfaceProps,
|
||||||
|
DataTableColumn,
|
||||||
|
DisclosureDefinition,
|
||||||
|
} from "./patterns/common-patterns.js";
|
||||||
|
|
||||||
|
export {
|
||||||
|
AsyncSurface,
|
||||||
|
EmptySurface,
|
||||||
|
LoadingSurface,
|
||||||
|
TerminalErrorSurface,
|
||||||
|
} from "../components/async-surface.jsx";
|
||||||
|
export { PageHeader } from "../components/page-header.jsx";
|
||||||
|
export {
|
||||||
|
AuthRequiredSurface,
|
||||||
|
ForbiddenSurface,
|
||||||
|
NotFoundSurface,
|
||||||
|
} from "../components/state-surfaces.jsx";
|
||||||
|
export {
|
||||||
|
DetailPage,
|
||||||
|
CollectionPage,
|
||||||
|
FormPage,
|
||||||
|
StandardPage,
|
||||||
|
StatusPage,
|
||||||
|
} from "../templates/index.js";
|
||||||
|
export {
|
||||||
|
DirtyNavigationDialog,
|
||||||
|
ErrorSummary,
|
||||||
|
Form,
|
||||||
|
FormActions,
|
||||||
|
FormField,
|
||||||
|
useAppForm,
|
||||||
|
useDirtyNavigationGuard,
|
||||||
|
} from "../forms/index.js";
|
||||||
|
export type {
|
||||||
|
PageActionDefinition,
|
||||||
|
PageHeading,
|
||||||
|
} from "../templates/page-templates.js";
|
||||||
|
export type { FormResult } from "../forms/form-contracts.js";
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { useId } from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
AuthRequiredSurface,
|
||||||
|
ForbiddenSurface,
|
||||||
|
NotFoundSurface,
|
||||||
|
} from "../../components/state-surfaces.jsx";
|
||||||
|
import { Button } from "../primitives/core.js";
|
||||||
|
import { Pagination } from "../primitives/navigation.js";
|
||||||
|
|
||||||
|
export type DataTableColumn<Row> = Readonly<{
|
||||||
|
id: string;
|
||||||
|
header: string;
|
||||||
|
cell(row: Row): React.ReactNode;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function DataTable<Row>({
|
||||||
|
caption,
|
||||||
|
columns,
|
||||||
|
rows,
|
||||||
|
rowKey,
|
||||||
|
empty,
|
||||||
|
}: Readonly<{
|
||||||
|
caption: string;
|
||||||
|
columns: readonly DataTableColumn<Row>[];
|
||||||
|
rows: readonly Row[];
|
||||||
|
rowKey(row: Row): string;
|
||||||
|
empty: React.ReactNode;
|
||||||
|
}>) {
|
||||||
|
if (rows.length === 0) return <>{empty}</>;
|
||||||
|
return (
|
||||||
|
<div className="ui-data-table__scroll" tabIndex={0}>
|
||||||
|
<table className="ui-data-table">
|
||||||
|
<caption>{caption}</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<th key={column.id} scope="col">
|
||||||
|
{column.header}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<tr key={rowKey(row)}>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<td key={column.id}>{column.cell(row)}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchFilterToolbar({
|
||||||
|
label,
|
||||||
|
search,
|
||||||
|
filters,
|
||||||
|
resetLabel,
|
||||||
|
onReset,
|
||||||
|
resultCount,
|
||||||
|
}: Readonly<{
|
||||||
|
label: string;
|
||||||
|
search: React.ReactNode;
|
||||||
|
filters?: React.ReactNode;
|
||||||
|
resetLabel: string;
|
||||||
|
onReset(): void;
|
||||||
|
resultCount: React.ReactNode;
|
||||||
|
}>) {
|
||||||
|
return (
|
||||||
|
<section aria-label={label} className="ui-search-filter-toolbar">
|
||||||
|
<div>{search}</div>
|
||||||
|
{filters ? <div>{filters}</div> : null}
|
||||||
|
<Button onClick={onReset} variant="ghost">
|
||||||
|
{resetLabel}
|
||||||
|
</Button>
|
||||||
|
<output>{resultCount}</output>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PaginationBar({
|
||||||
|
range,
|
||||||
|
...pagination
|
||||||
|
}: React.ComponentProps<typeof Pagination> & Readonly<{ range: string }>) {
|
||||||
|
return (
|
||||||
|
<div className="ui-pagination-bar">
|
||||||
|
<p>{range}</p>
|
||||||
|
<Pagination {...pagination} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DisclosureDefinition = Readonly<{
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
content: React.ReactNode;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function DisclosureGroup({
|
||||||
|
label,
|
||||||
|
items,
|
||||||
|
}: Readonly<{
|
||||||
|
label: string;
|
||||||
|
items: readonly DisclosureDefinition[];
|
||||||
|
}>) {
|
||||||
|
const groupId = useId();
|
||||||
|
return (
|
||||||
|
<section aria-labelledby={groupId} className="ui-disclosure-group">
|
||||||
|
<h2 className="visually-hidden" id={groupId}>
|
||||||
|
{label}
|
||||||
|
</h2>
|
||||||
|
{items.map((item) => (
|
||||||
|
<details key={item.id}>
|
||||||
|
<summary>{item.title}</summary>
|
||||||
|
<div>{item.content}</div>
|
||||||
|
</details>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AccessSurfaceProps =
|
||||||
|
| Readonly<{ kind: "auth-required"; onAction(): void }>
|
||||||
|
| Readonly<{ kind: "forbidden"; onAction(): void }>
|
||||||
|
| Readonly<{ kind: "not-found"; onAction(): void }>;
|
||||||
|
|
||||||
|
export function AccessSurface(props: AccessSurfaceProps) {
|
||||||
|
if (props.kind === "auth-required") {
|
||||||
|
return <AuthRequiredSurface onSignIn={props.onAction} />;
|
||||||
|
}
|
||||||
|
if (props.kind === "forbidden") {
|
||||||
|
return <ForbiddenSurface onNavigate={props.onAction} />;
|
||||||
|
}
|
||||||
|
return <NotFoundSurface onNavigate={props.onAction} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
import {
|
||||||
|
forwardRef,
|
||||||
|
useEffect,
|
||||||
|
useId,
|
||||||
|
useImperativeHandle,
|
||||||
|
useRef,
|
||||||
|
} from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
|
||||||
|
import { CloseIcon } from "../icons/semantic-icons.js";
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
|
||||||
|
export type ButtonVariant = "primary" | "secondary" | "danger" | "ghost";
|
||||||
|
export type ButtonSize = "default" | "compact";
|
||||||
|
|
||||||
|
export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> &
|
||||||
|
Readonly<{
|
||||||
|
variant?: ButtonVariant;
|
||||||
|
size?: ButtonSize;
|
||||||
|
pending?: boolean;
|
||||||
|
pendingLabel?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||||
|
function Button(
|
||||||
|
{
|
||||||
|
variant = "primary",
|
||||||
|
size = "default",
|
||||||
|
pending = false,
|
||||||
|
pendingLabel,
|
||||||
|
className = "",
|
||||||
|
type = "button",
|
||||||
|
children,
|
||||||
|
disabled,
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const classes = [
|
||||||
|
"ui-button",
|
||||||
|
`ui-button--${variant}`,
|
||||||
|
size === "compact" ? "ui-button--compact" : "",
|
||||||
|
pending ? "ui-button--pending" : "",
|
||||||
|
className,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
{...props}
|
||||||
|
aria-busy={pending || undefined}
|
||||||
|
className={classes}
|
||||||
|
disabled={disabled}
|
||||||
|
ref={ref}
|
||||||
|
type={type}
|
||||||
|
>
|
||||||
|
{pending ? (
|
||||||
|
<>
|
||||||
|
<Spinner decorative />
|
||||||
|
{pendingLabel ?? children}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
children
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type LinkButtonProps = React.AnchorHTMLAttributes<HTMLAnchorElement> &
|
||||||
|
Readonly<{
|
||||||
|
href: string;
|
||||||
|
variant?: ButtonVariant;
|
||||||
|
size?: ButtonSize;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const LinkButton = forwardRef<HTMLAnchorElement, LinkButtonProps>(
|
||||||
|
function LinkButton(
|
||||||
|
{
|
||||||
|
href,
|
||||||
|
variant = "primary",
|
||||||
|
size = "default",
|
||||||
|
className = "",
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
{...props}
|
||||||
|
className={[
|
||||||
|
"ui-button",
|
||||||
|
`ui-button--${variant}`,
|
||||||
|
size === "compact" ? "ui-button--compact" : "",
|
||||||
|
className,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" ")}
|
||||||
|
href={href}
|
||||||
|
ref={ref}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type IconButtonProps = Omit<ButtonProps, "aria-label" | "children"> &
|
||||||
|
Readonly<{
|
||||||
|
accessibleName: string;
|
||||||
|
children: React.ReactElement;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>(
|
||||||
|
function IconButton({ accessibleName, className = "", ...props }, ref) {
|
||||||
|
return (
|
||||||
|
<Button
|
||||||
|
{...props}
|
||||||
|
aria-label={accessibleName}
|
||||||
|
className={`ui-icon-button ${className}`.trim()}
|
||||||
|
ref={ref}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
type FieldFrameProps = Readonly<{
|
||||||
|
id?: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
error?: string;
|
||||||
|
required?: boolean;
|
||||||
|
className?: string;
|
||||||
|
children(
|
||||||
|
contract: Readonly<{
|
||||||
|
controlId: string;
|
||||||
|
describedBy: string | undefined;
|
||||||
|
invalid: boolean;
|
||||||
|
}>,
|
||||||
|
): React.ReactNode;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Field({
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
error,
|
||||||
|
required,
|
||||||
|
className = "",
|
||||||
|
children,
|
||||||
|
}: FieldFrameProps) {
|
||||||
|
const generatedId = useId();
|
||||||
|
const controlId = id ?? `field-${generatedId}`;
|
||||||
|
const descriptionId = description ? `${controlId}-description` : undefined;
|
||||||
|
const errorId = error ? `${controlId}-error` : undefined;
|
||||||
|
const describedBy = [descriptionId, errorId].filter(Boolean).join(" ");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`ui-field ${className}`.trim()}>
|
||||||
|
<label className="ui-field__label" htmlFor={controlId}>
|
||||||
|
{label}
|
||||||
|
{required ? <span aria-hidden="true"> *</span> : null}
|
||||||
|
</label>
|
||||||
|
{description ? (
|
||||||
|
<p className="ui-field__description" id={descriptionId}>
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
{children({
|
||||||
|
controlId,
|
||||||
|
describedBy: describedBy || undefined,
|
||||||
|
invalid: Boolean(error),
|
||||||
|
})}
|
||||||
|
{error ? (
|
||||||
|
<p className="ui-field__error" id={errorId}>
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TextFieldProps = Omit<
|
||||||
|
React.InputHTMLAttributes<HTMLInputElement>,
|
||||||
|
"id"
|
||||||
|
> &
|
||||||
|
Readonly<{
|
||||||
|
id?: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
error?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const TextField = forwardRef<HTMLInputElement, TextFieldProps>(
|
||||||
|
function TextField(
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
error,
|
||||||
|
className = "",
|
||||||
|
required,
|
||||||
|
...inputProps
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<Field
|
||||||
|
className={className}
|
||||||
|
description={description}
|
||||||
|
error={error}
|
||||||
|
id={id}
|
||||||
|
label={label}
|
||||||
|
required={required}
|
||||||
|
>
|
||||||
|
{({ controlId, describedBy, invalid }) => (
|
||||||
|
<input
|
||||||
|
{...inputProps}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={invalid || undefined}
|
||||||
|
className="ui-field__input"
|
||||||
|
id={controlId}
|
||||||
|
ref={ref}
|
||||||
|
required={required}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type CardProps = Readonly<{
|
||||||
|
title: string;
|
||||||
|
headingLevel?: 2 | 3 | 4;
|
||||||
|
description?: string;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
footer?: React.ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Card({
|
||||||
|
title,
|
||||||
|
headingLevel = 3,
|
||||||
|
description,
|
||||||
|
children,
|
||||||
|
footer,
|
||||||
|
className = "",
|
||||||
|
}: CardProps) {
|
||||||
|
const titleId = useId();
|
||||||
|
const Heading = `h${headingLevel}` as "h2" | "h3" | "h4";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
className={`ui-card ${className}`.trim()}
|
||||||
|
>
|
||||||
|
<div className="ui-card__header">
|
||||||
|
<Heading id={titleId}>{title}</Heading>
|
||||||
|
{description ? <p>{description}</p> : null}
|
||||||
|
</div>
|
||||||
|
{children ? <div className="ui-card__content">{children}</div> : null}
|
||||||
|
{footer ? <footer className="ui-card__footer">{footer}</footer> : null}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AlertProps = Readonly<{
|
||||||
|
title: string;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
variant?: "info" | "success" | "warning" | "danger";
|
||||||
|
dismissLabel?: string;
|
||||||
|
onDismiss?: () => void;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Alert({
|
||||||
|
title,
|
||||||
|
children,
|
||||||
|
variant = "info",
|
||||||
|
dismissLabel,
|
||||||
|
onDismiss,
|
||||||
|
}: AlertProps) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
className={`ui-alert ui-alert--${variant}`}
|
||||||
|
role={variant === "danger" ? "alert" : "status"}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<strong>{title}</strong>
|
||||||
|
{children ? <div className="ui-alert__content">{children}</div> : null}
|
||||||
|
</div>
|
||||||
|
{onDismiss ? (
|
||||||
|
<IconButton
|
||||||
|
accessibleName={
|
||||||
|
dismissLabel ?? message("action.alertCloseNamed", { title })
|
||||||
|
}
|
||||||
|
className="ui-alert__dismiss"
|
||||||
|
onClick={onDismiss}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BadgeProps = Readonly<{
|
||||||
|
children: React.ReactNode;
|
||||||
|
variant?: "neutral" | "info" | "success" | "warning" | "danger";
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Badge({ children, variant = "neutral" }: BadgeProps) {
|
||||||
|
return <span className={`ui-badge ui-badge--${variant}`}>{children}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type DialogProps = Readonly<{
|
||||||
|
open: boolean;
|
||||||
|
onClose(): void;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
closeLabel?: string;
|
||||||
|
children?: React.ReactNode;
|
||||||
|
actions?: React.ReactNode;
|
||||||
|
className?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
|
||||||
|
function Dialog(
|
||||||
|
{
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
closeLabel,
|
||||||
|
children,
|
||||||
|
actions,
|
||||||
|
className = "",
|
||||||
|
},
|
||||||
|
forwardedRef,
|
||||||
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
const dialogRef = useRef<HTMLDialogElement | null>(null);
|
||||||
|
const previousFocusRef = useRef<HTMLElement | null>(null);
|
||||||
|
const focusRestoreGenerationRef = useRef(0);
|
||||||
|
const titleId = useId();
|
||||||
|
const descriptionId = useId();
|
||||||
|
useImperativeHandle(forwardedRef, () => dialogRef.current!, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const dialog = dialogRef.current;
|
||||||
|
if (!dialog) return;
|
||||||
|
const generation = focusRestoreGenerationRef.current + 1;
|
||||||
|
focusRestoreGenerationRef.current = generation;
|
||||||
|
|
||||||
|
if (open) {
|
||||||
|
previousFocusRef.current =
|
||||||
|
document.activeElement instanceof HTMLElement
|
||||||
|
? document.activeElement
|
||||||
|
: null;
|
||||||
|
if (!dialog.open) {
|
||||||
|
if (typeof dialog.showModal === "function") dialog.showModal();
|
||||||
|
else dialog.setAttribute("open", "");
|
||||||
|
}
|
||||||
|
const firstFocusable = dialog.querySelector<HTMLElement>(
|
||||||
|
"[autofocus], button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])",
|
||||||
|
);
|
||||||
|
firstFocusable?.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dialog.open) {
|
||||||
|
if (typeof dialog.close === "function") dialog.close();
|
||||||
|
else dialog.removeAttribute("open");
|
||||||
|
}
|
||||||
|
const previousFocus = previousFocusRef.current;
|
||||||
|
previousFocusRef.current = null;
|
||||||
|
const restoreFocus = () => {
|
||||||
|
if (
|
||||||
|
focusRestoreGenerationRef.current === generation &&
|
||||||
|
previousFocus?.isConnected
|
||||||
|
) {
|
||||||
|
previousFocus.focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (typeof globalThis.requestAnimationFrame === "function") {
|
||||||
|
const frame = globalThis.requestAnimationFrame(restoreFocus);
|
||||||
|
return () => globalThis.cancelAnimationFrame(frame);
|
||||||
|
}
|
||||||
|
queueMicrotask(restoreFocus);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<dialog
|
||||||
|
aria-describedby={description ? descriptionId : undefined}
|
||||||
|
aria-labelledby={titleId}
|
||||||
|
className={`ui-dialog ${className}`.trim()}
|
||||||
|
onCancel={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
onClose();
|
||||||
|
}}
|
||||||
|
onClick={(event) => {
|
||||||
|
if (event.target === event.currentTarget) onClose();
|
||||||
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
event.preventDefault();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
ref={dialogRef}
|
||||||
|
>
|
||||||
|
<div className="ui-dialog__surface">
|
||||||
|
<header className="ui-dialog__header">
|
||||||
|
<div>
|
||||||
|
<h2 id={titleId}>{title}</h2>
|
||||||
|
{description ? <p id={descriptionId}>{description}</p> : null}
|
||||||
|
</div>
|
||||||
|
<IconButton
|
||||||
|
accessibleName={
|
||||||
|
closeLabel ?? message("action.closeNamed", { title })
|
||||||
|
}
|
||||||
|
className="ui-dialog__close"
|
||||||
|
onClick={onClose}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
</header>
|
||||||
|
{children ? (
|
||||||
|
<div className="ui-dialog__content">{children}</div>
|
||||||
|
) : null}
|
||||||
|
{actions ? (
|
||||||
|
<footer className="ui-dialog__actions">{actions}</footer>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</dialog>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type SpinnerProps =
|
||||||
|
| Readonly<{ decorative: true; label?: never }>
|
||||||
|
| Readonly<{ decorative?: false; label: string }>;
|
||||||
|
|
||||||
|
export function Spinner(props: SpinnerProps) {
|
||||||
|
const accessibility = props.decorative
|
||||||
|
? { "aria-hidden": true as const }
|
||||||
|
: { "aria-label": props.label, role: "status" };
|
||||||
|
return <span {...accessibility} className="ui-spinner" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function VisuallyHidden({
|
||||||
|
children,
|
||||||
|
}: Readonly<{ children: React.ReactNode }>) {
|
||||||
|
return <span className="visually-hidden">{children}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Portal({
|
||||||
|
children,
|
||||||
|
}: Readonly<{ children: React.ReactNode }>) {
|
||||||
|
if (typeof document === "undefined") return <>{children}</>;
|
||||||
|
return createPortal(children, document.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FocusRing({
|
||||||
|
children,
|
||||||
|
}: Readonly<{ children: React.ReactNode }>) {
|
||||||
|
return <span className="ui-focus-ring">{children}</span>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
export type ProgressBarProps = Readonly<{
|
||||||
|
label: string;
|
||||||
|
value?: number;
|
||||||
|
max?: number;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function ProgressBar({ label, value, max = 100 }: ProgressBarProps) {
|
||||||
|
const determinate = typeof value === "number";
|
||||||
|
return (
|
||||||
|
<div className="ui-progress">
|
||||||
|
<div className="ui-progress__label">
|
||||||
|
<span>{label}</span>
|
||||||
|
{determinate ? <span>{Math.round((value / max) * 100)}%</span> : null}
|
||||||
|
</div>
|
||||||
|
<progress
|
||||||
|
aria-label={label}
|
||||||
|
className="ui-progress__bar"
|
||||||
|
max={max}
|
||||||
|
value={determinate ? Math.min(Math.max(value, 0), max) : undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SkeletonProps = Readonly<{
|
||||||
|
label?: string;
|
||||||
|
height?: "text" | "control" | "surface";
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Skeleton({
|
||||||
|
label,
|
||||||
|
height = "surface",
|
||||||
|
}: SkeletonProps) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
aria-label={label}
|
||||||
|
aria-hidden={label ? undefined : true}
|
||||||
|
className={`ui-skeleton ui-skeleton--${height}`}
|
||||||
|
role={label ? "status" : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Separator({
|
||||||
|
label,
|
||||||
|
decorative = true,
|
||||||
|
}: Readonly<{ label?: string; decorative?: boolean }>) {
|
||||||
|
return (
|
||||||
|
<hr
|
||||||
|
aria-label={decorative ? undefined : label}
|
||||||
|
aria-hidden={decorative || undefined}
|
||||||
|
className="ui-separator"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,411 @@
|
|||||||
|
import {
|
||||||
|
forwardRef,
|
||||||
|
useEffect,
|
||||||
|
useId,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
|
||||||
|
import { CloseIcon, SearchIcon } from "../icons/semantic-icons.js";
|
||||||
|
import { Field, IconButton } from "./core.js";
|
||||||
|
import type { TextFieldProps } from "./core.js";
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
|
||||||
|
type FieldCopy = Readonly<{
|
||||||
|
id?: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
error?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type TextAreaProps = Omit<
|
||||||
|
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
|
||||||
|
"id"
|
||||||
|
> &
|
||||||
|
FieldCopy &
|
||||||
|
Readonly<{ maxLengthMessage?: (remaining: number) => string }>;
|
||||||
|
|
||||||
|
export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
|
||||||
|
function TextArea(
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
error,
|
||||||
|
required,
|
||||||
|
className = "",
|
||||||
|
maxLength,
|
||||||
|
maxLengthMessage,
|
||||||
|
value,
|
||||||
|
defaultValue,
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
const [uncontrolledValue, setUncontrolledValue] = useState(
|
||||||
|
String(defaultValue ?? ""),
|
||||||
|
);
|
||||||
|
const currentValue =
|
||||||
|
value === undefined ? uncontrolledValue : String(value ?? "");
|
||||||
|
const remaining =
|
||||||
|
typeof maxLength === "number" ? maxLength - currentValue.length : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Field
|
||||||
|
className={className}
|
||||||
|
description={description}
|
||||||
|
error={error}
|
||||||
|
id={id}
|
||||||
|
label={label}
|
||||||
|
required={required}
|
||||||
|
>
|
||||||
|
{({ controlId, describedBy, invalid }) => (
|
||||||
|
<>
|
||||||
|
<textarea
|
||||||
|
{...props}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={invalid || undefined}
|
||||||
|
className="ui-field__input ui-field__textarea"
|
||||||
|
defaultValue={value === undefined ? defaultValue : undefined}
|
||||||
|
id={controlId}
|
||||||
|
maxLength={maxLength}
|
||||||
|
onChange={(event) => {
|
||||||
|
if (value === undefined) setUncontrolledValue(event.currentTarget.value);
|
||||||
|
props.onChange?.(event);
|
||||||
|
}}
|
||||||
|
ref={ref}
|
||||||
|
required={required}
|
||||||
|
value={value}
|
||||||
|
/>
|
||||||
|
{remaining !== null ? (
|
||||||
|
<output className="ui-field__counter">
|
||||||
|
{maxLengthMessage
|
||||||
|
? maxLengthMessage(remaining)
|
||||||
|
: message("form.remaining", { count: remaining })}
|
||||||
|
</output>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type SelectOption = Readonly<{
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type SelectProps = Omit<
|
||||||
|
React.SelectHTMLAttributes<HTMLSelectElement>,
|
||||||
|
"id" | "children"
|
||||||
|
> &
|
||||||
|
FieldCopy &
|
||||||
|
Readonly<{
|
||||||
|
options: readonly SelectOption[];
|
||||||
|
placeholder?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const Select = forwardRef<HTMLSelectElement, SelectProps>(
|
||||||
|
function Select(
|
||||||
|
{
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
error,
|
||||||
|
options,
|
||||||
|
placeholder,
|
||||||
|
required,
|
||||||
|
className = "",
|
||||||
|
...props
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<Field
|
||||||
|
className={className}
|
||||||
|
description={description}
|
||||||
|
error={error}
|
||||||
|
id={id}
|
||||||
|
label={label}
|
||||||
|
required={required}
|
||||||
|
>
|
||||||
|
{({ controlId, describedBy, invalid }) => (
|
||||||
|
<select
|
||||||
|
{...props}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={invalid || undefined}
|
||||||
|
className="ui-field__input ui-field__select"
|
||||||
|
id={controlId}
|
||||||
|
ref={ref}
|
||||||
|
required={required}
|
||||||
|
>
|
||||||
|
{placeholder ? (
|
||||||
|
<option disabled value="">
|
||||||
|
{placeholder}
|
||||||
|
</option>
|
||||||
|
) : null}
|
||||||
|
{options.map((option) => (
|
||||||
|
<option
|
||||||
|
disabled={option.disabled}
|
||||||
|
key={option.value}
|
||||||
|
value={option.value}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type CheckboxProps = Omit<
|
||||||
|
React.InputHTMLAttributes<HTMLInputElement>,
|
||||||
|
"type"
|
||||||
|
> &
|
||||||
|
Readonly<{
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
error?: string;
|
||||||
|
indeterminate?: boolean;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
|
||||||
|
function Checkbox(
|
||||||
|
{ label, description, error, indeterminate = false, id, ...props },
|
||||||
|
forwardedRef,
|
||||||
|
) {
|
||||||
|
const generatedId = useId();
|
||||||
|
const controlId = id ?? `checkbox-${generatedId}`;
|
||||||
|
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||||
|
const descriptionId = description ? `${controlId}-description` : undefined;
|
||||||
|
const errorId = error ? `${controlId}-error` : undefined;
|
||||||
|
useEffect(() => {
|
||||||
|
if (inputRef.current) inputRef.current.indeterminate = indeterminate;
|
||||||
|
}, [indeterminate]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ui-choice-field">
|
||||||
|
<label className="ui-choice-field__control" htmlFor={controlId}>
|
||||||
|
<input
|
||||||
|
{...props}
|
||||||
|
aria-describedby={
|
||||||
|
[descriptionId, errorId].filter(Boolean).join(" ") || undefined
|
||||||
|
}
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
id={controlId}
|
||||||
|
ref={(node) => {
|
||||||
|
inputRef.current = node;
|
||||||
|
if (typeof forwardedRef === "function") forwardedRef(node);
|
||||||
|
else if (forwardedRef) forwardedRef.current = node;
|
||||||
|
}}
|
||||||
|
type="checkbox"
|
||||||
|
/>
|
||||||
|
<span>{label}</span>
|
||||||
|
</label>
|
||||||
|
{description ? (
|
||||||
|
<p className="ui-field__description" id={descriptionId}>
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
{error ? (
|
||||||
|
<p className="ui-field__error" id={errorId}>
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export type RadioOption = Readonly<{
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type RadioGroupProps = Readonly<{
|
||||||
|
name: string;
|
||||||
|
label: string;
|
||||||
|
options: readonly RadioOption[];
|
||||||
|
value?: string;
|
||||||
|
defaultValue?: string;
|
||||||
|
onChange?(value: string): void;
|
||||||
|
disabled?: boolean;
|
||||||
|
error?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function RadioGroup({
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
options,
|
||||||
|
value,
|
||||||
|
defaultValue,
|
||||||
|
onChange,
|
||||||
|
disabled,
|
||||||
|
error,
|
||||||
|
}: RadioGroupProps) {
|
||||||
|
const [internalValue, setInternalValue] = useState(defaultValue ?? "");
|
||||||
|
const selected = value ?? internalValue;
|
||||||
|
const errorId = useId();
|
||||||
|
const refs = useRef<Array<HTMLInputElement | null>>([]);
|
||||||
|
|
||||||
|
function choose(nextValue: string) {
|
||||||
|
if (value === undefined) setInternalValue(nextValue);
|
||||||
|
onChange?.(nextValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<fieldset
|
||||||
|
aria-describedby={error ? errorId : undefined}
|
||||||
|
className="ui-radio-group"
|
||||||
|
disabled={disabled}
|
||||||
|
>
|
||||||
|
<legend>{label}</legend>
|
||||||
|
{options.map((option, index) => (
|
||||||
|
<label className="ui-choice-field__control" key={option.value}>
|
||||||
|
<input
|
||||||
|
checked={selected === option.value}
|
||||||
|
disabled={option.disabled}
|
||||||
|
name={name}
|
||||||
|
onChange={() => choose(option.value)}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (!["ArrowDown", "ArrowRight", "ArrowUp", "ArrowLeft"].includes(event.key)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
const direction =
|
||||||
|
event.key === "ArrowDown" || event.key === "ArrowRight" ? 1 : -1;
|
||||||
|
let next = index;
|
||||||
|
do {
|
||||||
|
next = (next + direction + options.length) % options.length;
|
||||||
|
} while (options[next]?.disabled && next !== index);
|
||||||
|
const nextOption = options[next];
|
||||||
|
if (nextOption && !nextOption.disabled) {
|
||||||
|
choose(nextOption.value);
|
||||||
|
refs.current[next]?.focus();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
ref={(node) => {
|
||||||
|
refs.current[index] = node;
|
||||||
|
}}
|
||||||
|
type="radio"
|
||||||
|
value={option.value}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
{option.label}
|
||||||
|
{option.description ? <small>{option.description}</small> : null}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
{error ? (
|
||||||
|
<p className="ui-field__error" id={errorId}>
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</fieldset>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SwitchProps = Readonly<{
|
||||||
|
label: string;
|
||||||
|
checked: boolean;
|
||||||
|
onChange(checked: boolean): void;
|
||||||
|
disabled?: boolean;
|
||||||
|
description?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Switch({
|
||||||
|
label,
|
||||||
|
checked,
|
||||||
|
onChange,
|
||||||
|
disabled,
|
||||||
|
description,
|
||||||
|
}: SwitchProps) {
|
||||||
|
const descriptionId = useId();
|
||||||
|
return (
|
||||||
|
<div className="ui-switch-field">
|
||||||
|
<button
|
||||||
|
aria-checked={checked}
|
||||||
|
aria-describedby={description ? descriptionId : undefined}
|
||||||
|
className="ui-switch"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => onChange(!checked)}
|
||||||
|
role="switch"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<span aria-hidden="true" className="ui-switch__thumb" />
|
||||||
|
<span>{label}</span>
|
||||||
|
</button>
|
||||||
|
{description ? (
|
||||||
|
<p className="ui-field__description" id={descriptionId}>
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SearchFieldProps = Omit<TextFieldProps, "type"> &
|
||||||
|
Readonly<{
|
||||||
|
clearLabel: string;
|
||||||
|
onClear(): void;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(
|
||||||
|
function SearchField(
|
||||||
|
{
|
||||||
|
clearLabel,
|
||||||
|
onClear,
|
||||||
|
value,
|
||||||
|
className = "",
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
error,
|
||||||
|
required,
|
||||||
|
...inputProps
|
||||||
|
},
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
return (
|
||||||
|
<div className={`ui-search-field ${className}`.trim()}>
|
||||||
|
<SearchIcon />
|
||||||
|
<Field
|
||||||
|
description={description}
|
||||||
|
error={error}
|
||||||
|
id={id}
|
||||||
|
label={label}
|
||||||
|
required={required}
|
||||||
|
>
|
||||||
|
{({ controlId, describedBy, invalid }) => (
|
||||||
|
<input
|
||||||
|
{...inputProps}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
aria-invalid={invalid || undefined}
|
||||||
|
className="ui-field__input"
|
||||||
|
id={controlId}
|
||||||
|
ref={ref}
|
||||||
|
type="search"
|
||||||
|
value={value}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
{String(value ?? "").length > 0 ? (
|
||||||
|
<IconButton
|
||||||
|
accessibleName={clearLabel}
|
||||||
|
onClick={onClear}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import { useId, useRef, useState } from "react";
|
||||||
|
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
import { NextIcon, PreviousIcon } from "../icons/semantic-icons.js";
|
||||||
|
import { IconButton, LinkButton } from "./core.js";
|
||||||
|
|
||||||
|
export type BreadcrumbItem = Readonly<{
|
||||||
|
label: string;
|
||||||
|
href?: string;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Breadcrumbs({
|
||||||
|
label,
|
||||||
|
items,
|
||||||
|
}: Readonly<{ label: string; items: readonly BreadcrumbItem[] }>) {
|
||||||
|
return (
|
||||||
|
<nav aria-label={label} className="ui-breadcrumbs">
|
||||||
|
<ol>
|
||||||
|
{items.map((item, index) => {
|
||||||
|
const current = index === items.length - 1;
|
||||||
|
return (
|
||||||
|
<li key={`${item.label}-${index}`}>
|
||||||
|
{item.href && !current ? (
|
||||||
|
<a href={item.href}>{item.label}</a>
|
||||||
|
) : (
|
||||||
|
<span aria-current={current ? "page" : undefined}>
|
||||||
|
{item.label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ol>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TabDefinition = Readonly<{
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
panel: React.ReactNode;
|
||||||
|
disabled?: boolean;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Tabs({
|
||||||
|
label,
|
||||||
|
tabs,
|
||||||
|
value,
|
||||||
|
defaultValue,
|
||||||
|
activation = "automatic",
|
||||||
|
onChange,
|
||||||
|
}: Readonly<{
|
||||||
|
label: string;
|
||||||
|
tabs: readonly TabDefinition[];
|
||||||
|
value?: string;
|
||||||
|
defaultValue?: string;
|
||||||
|
activation?: "automatic" | "manual";
|
||||||
|
onChange?(id: string): void;
|
||||||
|
}>) {
|
||||||
|
const fallback = tabs.find((tab) => !tab.disabled)?.id ?? "";
|
||||||
|
const [internalValue, setInternalValue] = useState(defaultValue ?? fallback);
|
||||||
|
const [focusValue, setFocusValue] = useState(value ?? internalValue);
|
||||||
|
const selected = value ?? internalValue;
|
||||||
|
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
|
||||||
|
const baseId = useId();
|
||||||
|
const { direction } = useLocale();
|
||||||
|
|
||||||
|
function select(id: string) {
|
||||||
|
if (value === undefined) setInternalValue(id);
|
||||||
|
onChange?.(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function move(currentIndex: number, direction: 1 | -1) {
|
||||||
|
let next = currentIndex;
|
||||||
|
do {
|
||||||
|
next = (next + direction + tabs.length) % tabs.length;
|
||||||
|
} while (tabs[next]?.disabled && next !== currentIndex);
|
||||||
|
const nextTab = tabs[next];
|
||||||
|
if (!nextTab || nextTab.disabled) return;
|
||||||
|
setFocusValue(nextTab.id);
|
||||||
|
if (activation === "automatic") select(nextTab.id);
|
||||||
|
tabRefs.current[next]?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ui-tabs">
|
||||||
|
<div aria-label={label} className="ui-tabs__list" role="tablist">
|
||||||
|
{tabs.map((tab, index) => (
|
||||||
|
<button
|
||||||
|
aria-controls={`${baseId}-${tab.id}-panel`}
|
||||||
|
aria-selected={selected === tab.id}
|
||||||
|
className="ui-tabs__tab"
|
||||||
|
disabled={tab.disabled}
|
||||||
|
id={`${baseId}-${tab.id}-tab`}
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => {
|
||||||
|
setFocusValue(tab.id);
|
||||||
|
select(tab.id);
|
||||||
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "ArrowRight") {
|
||||||
|
event.preventDefault();
|
||||||
|
move(index, direction === "rtl" ? -1 : 1);
|
||||||
|
} else if (event.key === "ArrowLeft") {
|
||||||
|
event.preventDefault();
|
||||||
|
move(index, direction === "rtl" ? 1 : -1);
|
||||||
|
} else if (
|
||||||
|
activation === "manual" &&
|
||||||
|
(event.key === "Enter" || event.key === " ")
|
||||||
|
) {
|
||||||
|
event.preventDefault();
|
||||||
|
select(tab.id);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
ref={(node) => {
|
||||||
|
tabRefs.current[index] = node;
|
||||||
|
}}
|
||||||
|
role="tab"
|
||||||
|
tabIndex={focusValue === tab.id ? 0 : -1}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{tabs.map((tab) => (
|
||||||
|
<div
|
||||||
|
aria-labelledby={`${baseId}-${tab.id}-tab`}
|
||||||
|
className="ui-tabs__panel"
|
||||||
|
hidden={selected !== tab.id}
|
||||||
|
id={`${baseId}-${tab.id}-panel`}
|
||||||
|
key={tab.id}
|
||||||
|
role="tabpanel"
|
||||||
|
tabIndex={0}
|
||||||
|
>
|
||||||
|
{tab.panel}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Pagination({
|
||||||
|
label,
|
||||||
|
page,
|
||||||
|
pageCount,
|
||||||
|
previousLabel,
|
||||||
|
nextLabel,
|
||||||
|
pageLabel,
|
||||||
|
onChange,
|
||||||
|
}: Readonly<{
|
||||||
|
label: string;
|
||||||
|
page: number;
|
||||||
|
pageCount: number;
|
||||||
|
previousLabel: string;
|
||||||
|
nextLabel: string;
|
||||||
|
pageLabel(page: number): string;
|
||||||
|
onChange(page: number): void;
|
||||||
|
}>) {
|
||||||
|
const pages = Array.from({ length: pageCount }, (_, index) => index + 1);
|
||||||
|
const { direction } = useLocale();
|
||||||
|
const PreviousDirectionalIcon =
|
||||||
|
direction === "rtl" ? NextIcon : PreviousIcon;
|
||||||
|
const NextDirectionalIcon = direction === "rtl" ? PreviousIcon : NextIcon;
|
||||||
|
return (
|
||||||
|
<nav aria-label={label} className="ui-pagination">
|
||||||
|
<IconButton
|
||||||
|
accessibleName={previousLabel}
|
||||||
|
disabled={page <= 1}
|
||||||
|
onClick={() => onChange(page - 1)}
|
||||||
|
variant="secondary"
|
||||||
|
>
|
||||||
|
<PreviousDirectionalIcon />
|
||||||
|
</IconButton>
|
||||||
|
{pages.map((candidate) => (
|
||||||
|
<LinkButton
|
||||||
|
aria-current={candidate === page ? "page" : undefined}
|
||||||
|
href={`?page=${candidate}`}
|
||||||
|
key={candidate}
|
||||||
|
onClick={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
onChange(candidate);
|
||||||
|
}}
|
||||||
|
variant={candidate === page ? "primary" : "ghost"}
|
||||||
|
>
|
||||||
|
{pageLabel(candidate)}
|
||||||
|
</LinkButton>
|
||||||
|
))}
|
||||||
|
<IconButton
|
||||||
|
accessibleName={nextLabel}
|
||||||
|
disabled={page >= pageCount}
|
||||||
|
onClick={() => onChange(page + 1)}
|
||||||
|
variant="secondary"
|
||||||
|
>
|
||||||
|
<NextDirectionalIcon />
|
||||||
|
</IconButton>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
import {
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useId,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
|
||||||
|
import { CloseIcon } from "../icons/semantic-icons.js";
|
||||||
|
import { Button, Dialog, IconButton } from "./core.js";
|
||||||
|
import { useLocale } from "../../i18n/index.js";
|
||||||
|
|
||||||
|
export type DrawerProps = Readonly<{
|
||||||
|
open: boolean;
|
||||||
|
onClose(): void;
|
||||||
|
title: string;
|
||||||
|
closeLabel?: string;
|
||||||
|
placement?: "start" | "end";
|
||||||
|
children: React.ReactNode;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Drawer({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
title,
|
||||||
|
closeLabel,
|
||||||
|
placement = "start",
|
||||||
|
children,
|
||||||
|
}: DrawerProps) {
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
className={`ui-drawer ui-drawer--${placement}`}
|
||||||
|
closeLabel={closeLabel}
|
||||||
|
onClose={onClose}
|
||||||
|
open={open}
|
||||||
|
title={title}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PopoverProps = Readonly<{
|
||||||
|
triggerLabel: string;
|
||||||
|
children: React.ReactNode;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Popover({ triggerLabel, children }: PopoverProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||||
|
const contentId = useId();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
function closeOutside(event: PointerEvent) {
|
||||||
|
if (
|
||||||
|
event.target instanceof Node &&
|
||||||
|
!rootRef.current?.contains(event.target)
|
||||||
|
) {
|
||||||
|
setOpen(false);
|
||||||
|
triggerRef.current?.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function closeOnEscape(event: KeyboardEvent) {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
setOpen(false);
|
||||||
|
triggerRef.current?.focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener("pointerdown", closeOutside);
|
||||||
|
document.addEventListener("keydown", closeOnEscape);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("pointerdown", closeOutside);
|
||||||
|
document.removeEventListener("keydown", closeOnEscape);
|
||||||
|
};
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ui-popover" ref={rootRef}>
|
||||||
|
<Button
|
||||||
|
aria-controls={contentId}
|
||||||
|
aria-expanded={open}
|
||||||
|
onClick={() => setOpen((current) => !current)}
|
||||||
|
ref={triggerRef}
|
||||||
|
variant="secondary"
|
||||||
|
>
|
||||||
|
{triggerLabel}
|
||||||
|
</Button>
|
||||||
|
{open ? (
|
||||||
|
<div className="ui-popover__content" id={contentId} role="dialog">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TooltipProps = Readonly<{
|
||||||
|
content: string;
|
||||||
|
children: React.ReactElement;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Tooltip({ content, children }: TooltipProps) {
|
||||||
|
const tooltipId = useId();
|
||||||
|
return (
|
||||||
|
<span className="ui-tooltip">
|
||||||
|
<span aria-describedby={tooltipId} className="ui-tooltip__trigger">
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
<span className="ui-tooltip__content" id={tooltipId} role="tooltip">
|
||||||
|
{content}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MenuItemDefinition = Readonly<{
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
onSelect(): void;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export type MenuProps = Readonly<{
|
||||||
|
triggerLabel: string;
|
||||||
|
items: readonly MenuItemDefinition[];
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export function Menu({ triggerLabel, items }: MenuProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [activeIndex, setActiveIndex] = useState(0);
|
||||||
|
const triggerRef = useRef<HTMLButtonElement | null>(null);
|
||||||
|
const rootRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
|
||||||
|
const searchRef = useRef("");
|
||||||
|
const resetSearchRef = useRef<number | undefined>(undefined);
|
||||||
|
|
||||||
|
const enabledIndexes = useMemo(
|
||||||
|
() => items.flatMap((item, index) => (item.disabled ? [] : [index])),
|
||||||
|
[items],
|
||||||
|
);
|
||||||
|
|
||||||
|
const focusIndex = useCallback(
|
||||||
|
(index: number) => {
|
||||||
|
setActiveIndex(index);
|
||||||
|
queueMicrotask(() => itemRefs.current[index]?.focus());
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
function openAt(index: number) {
|
||||||
|
setOpen(true);
|
||||||
|
focusIndex(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dismiss() {
|
||||||
|
setOpen(false);
|
||||||
|
queueMicrotask(() => triggerRef.current?.focus());
|
||||||
|
}
|
||||||
|
|
||||||
|
function move(direction: 1 | -1) {
|
||||||
|
const currentPosition = Math.max(enabledIndexes.indexOf(activeIndex), 0);
|
||||||
|
const nextPosition =
|
||||||
|
(currentPosition + direction + enabledIndexes.length) %
|
||||||
|
enabledIndexes.length;
|
||||||
|
const nextIndex = enabledIndexes[nextPosition];
|
||||||
|
if (nextIndex !== undefined) focusIndex(nextIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
function closeOutside(event: PointerEvent) {
|
||||||
|
if (
|
||||||
|
event.target instanceof Node &&
|
||||||
|
!rootRef.current?.contains(event.target)
|
||||||
|
) {
|
||||||
|
setOpen(false);
|
||||||
|
queueMicrotask(() => triggerRef.current?.focus());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener("pointerdown", closeOutside);
|
||||||
|
return () => document.removeEventListener("pointerdown", closeOutside);
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="ui-menu" ref={rootRef}>
|
||||||
|
<Button
|
||||||
|
aria-expanded={open}
|
||||||
|
aria-haspopup="menu"
|
||||||
|
onClick={() => {
|
||||||
|
if (open) dismiss();
|
||||||
|
else openAt(enabledIndexes[0] ?? 0);
|
||||||
|
}}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "ArrowDown") {
|
||||||
|
event.preventDefault();
|
||||||
|
openAt(enabledIndexes[0] ?? 0);
|
||||||
|
}
|
||||||
|
if (event.key === "ArrowUp") {
|
||||||
|
event.preventDefault();
|
||||||
|
openAt(enabledIndexes.at(-1) ?? 0);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
ref={triggerRef}
|
||||||
|
variant="secondary"
|
||||||
|
>
|
||||||
|
{triggerLabel}
|
||||||
|
</Button>
|
||||||
|
{open ? (
|
||||||
|
<div
|
||||||
|
className="ui-menu__content"
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
event.preventDefault();
|
||||||
|
dismiss();
|
||||||
|
} else if (event.key === "ArrowDown") {
|
||||||
|
event.preventDefault();
|
||||||
|
move(1);
|
||||||
|
} else if (event.key === "ArrowUp") {
|
||||||
|
event.preventDefault();
|
||||||
|
move(-1);
|
||||||
|
} else if (event.key === "Home") {
|
||||||
|
event.preventDefault();
|
||||||
|
focusIndex(enabledIndexes[0] ?? 0);
|
||||||
|
} else if (event.key === "End") {
|
||||||
|
event.preventDefault();
|
||||||
|
focusIndex(enabledIndexes.at(-1) ?? 0);
|
||||||
|
} else if (
|
||||||
|
event.key.length === 1 &&
|
||||||
|
!event.ctrlKey &&
|
||||||
|
!event.metaKey &&
|
||||||
|
!event.altKey
|
||||||
|
) {
|
||||||
|
searchRef.current += event.key.toLocaleLowerCase();
|
||||||
|
window.clearTimeout(resetSearchRef.current);
|
||||||
|
resetSearchRef.current = window.setTimeout(() => {
|
||||||
|
searchRef.current = "";
|
||||||
|
}, 500);
|
||||||
|
const match = items.findIndex(
|
||||||
|
(item) =>
|
||||||
|
!item.disabled &&
|
||||||
|
item.label
|
||||||
|
.toLocaleLowerCase()
|
||||||
|
.startsWith(searchRef.current),
|
||||||
|
);
|
||||||
|
if (match >= 0) focusIndex(match);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
role="menu"
|
||||||
|
>
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<button
|
||||||
|
className="ui-menu__item"
|
||||||
|
disabled={item.disabled}
|
||||||
|
key={item.id}
|
||||||
|
onClick={() => {
|
||||||
|
item.onSelect();
|
||||||
|
dismiss();
|
||||||
|
}}
|
||||||
|
ref={(node) => {
|
||||||
|
itemRefs.current[index] = node;
|
||||||
|
}}
|
||||||
|
role="menuitem"
|
||||||
|
tabIndex={index === activeIndex ? 0 : -1}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type ToastTone = "info" | "success" | "warning" | "danger";
|
||||||
|
type ToastInput = Readonly<{
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
tone?: ToastTone;
|
||||||
|
durationMs?: number;
|
||||||
|
}>;
|
||||||
|
type ToastEntry = ToastInput & Readonly<{ count: number }>;
|
||||||
|
type ToastContextValue = Readonly<{
|
||||||
|
push(toast: ToastInput): void;
|
||||||
|
dismiss(id: string): void;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
const ToastContext = createContext<ToastContextValue | null>(null);
|
||||||
|
|
||||||
|
export function ToastProvider({
|
||||||
|
children,
|
||||||
|
limit = 3,
|
||||||
|
}: Readonly<{ children: React.ReactNode; limit?: number }>) {
|
||||||
|
const [toasts, setToasts] = useState<readonly ToastEntry[]>([]);
|
||||||
|
|
||||||
|
const dismiss = useCallback((id: string) => {
|
||||||
|
setToasts((current) => current.filter((toast) => toast.id !== id));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const push = useCallback(
|
||||||
|
(toast: ToastInput) => {
|
||||||
|
setToasts((current) => {
|
||||||
|
const existing = current.find((entry) => entry.id === toast.id);
|
||||||
|
if (existing) {
|
||||||
|
return current.map((entry) =>
|
||||||
|
entry.id === toast.id
|
||||||
|
? { ...entry, ...toast, count: entry.count + 1 }
|
||||||
|
: entry,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return [...current, { ...toast, count: 1 }].slice(-limit);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[limit],
|
||||||
|
);
|
||||||
|
|
||||||
|
const value = useMemo(() => ({ push, dismiss }), [dismiss, push]);
|
||||||
|
return (
|
||||||
|
<ToastContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
<ToastRegion dismiss={dismiss} toasts={toasts} />
|
||||||
|
</ToastContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useToast() {
|
||||||
|
const context = useContext(ToastContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error("ToastProvider is required.");
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToastRegion({
|
||||||
|
toasts,
|
||||||
|
dismiss,
|
||||||
|
}: Readonly<{
|
||||||
|
toasts: readonly ToastEntry[];
|
||||||
|
dismiss(id: string): void;
|
||||||
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
aria-label={message("toast.region")}
|
||||||
|
aria-live="polite"
|
||||||
|
className="ui-toast-region"
|
||||||
|
>
|
||||||
|
{toasts.map((toast) => (
|
||||||
|
<ToastItem dismiss={dismiss} key={toast.id} toast={toast} />
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToastItem({
|
||||||
|
toast,
|
||||||
|
dismiss,
|
||||||
|
}: Readonly<{
|
||||||
|
toast: ToastEntry;
|
||||||
|
dismiss(id: string): void;
|
||||||
|
}>) {
|
||||||
|
const { message } = useLocale();
|
||||||
|
const [paused, setPaused] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (paused) return;
|
||||||
|
const timeout = window.setTimeout(
|
||||||
|
() => dismiss(toast.id),
|
||||||
|
toast.durationMs ?? 5000,
|
||||||
|
);
|
||||||
|
return () => window.clearTimeout(timeout);
|
||||||
|
}, [dismiss, paused, toast.durationMs, toast.id, toast.count]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
className={`ui-toast ui-toast--${toast.tone ?? "info"}`}
|
||||||
|
onBlur={(event) => {
|
||||||
|
if (!event.currentTarget.contains(event.relatedTarget)) setPaused(false);
|
||||||
|
}}
|
||||||
|
onFocus={() => setPaused(true)}
|
||||||
|
onMouseEnter={() => setPaused(true)}
|
||||||
|
onMouseLeave={() => setPaused(false)}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<strong>{toast.title}</strong>
|
||||||
|
{toast.count > 1 ? (
|
||||||
|
<span className="ui-toast__count"> ×{toast.count}</span>
|
||||||
|
) : null}
|
||||||
|
{toast.description ? <p>{toast.description}</p> : null}
|
||||||
|
</div>
|
||||||
|
<IconButton
|
||||||
|
accessibleName={message("action.closeNamed", { title: toast.title })}
|
||||||
|
onClick={() => dismiss(toast.id)}
|
||||||
|
variant="ghost"
|
||||||
|
>
|
||||||
|
<CloseIcon />
|
||||||
|
</IconButton>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ConfirmationDialog({
|
||||||
|
open,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
confirmLabel,
|
||||||
|
cancelLabel,
|
||||||
|
danger = false,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
}: Readonly<{
|
||||||
|
open: boolean;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
confirmLabel: string;
|
||||||
|
cancelLabel: string;
|
||||||
|
danger?: boolean;
|
||||||
|
onConfirm(): void;
|
||||||
|
onCancel(): void;
|
||||||
|
}>) {
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
actions={
|
||||||
|
<>
|
||||||
|
<Button onClick={onCancel} variant="secondary">
|
||||||
|
{cancelLabel}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={onConfirm} variant={danger ? "danger" : "primary"}>
|
||||||
|
{confirmLabel}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
description={description}
|
||||||
|
onClose={onCancel}
|
||||||
|
open={open}
|
||||||
|
title={title}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
@theme {
|
||||||
|
--button-primary-background: var(--color-action);
|
||||||
|
--button-primary-content: var(--color-on-action);
|
||||||
|
--button-primary-hover: var(--color-action-hover);
|
||||||
|
--field-border: var(--color-border-strong);
|
||||||
|
--field-border-invalid: var(--color-danger);
|
||||||
|
--dialog-elevation: var(--elevation-dialog);
|
||||||
|
--navigation-active-background: color-mix(
|
||||||
|
in oklch,
|
||||||
|
var(--color-action) 14%,
|
||||||
|
var(--color-panel)
|
||||||
|
);
|
||||||
|
--drawer-width: min(20rem, 88vw);
|
||||||
|
--toast-width: min(24rem, calc(100vw - 2rem));
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (forced-colors: active) {
|
||||||
|
:root {
|
||||||
|
--color-border: CanvasText;
|
||||||
|
--color-border-strong: CanvasText;
|
||||||
|
--color-focus: Highlight;
|
||||||
|
--color-action: LinkText;
|
||||||
|
--color-danger: MarkText;
|
||||||
|
--color-danger-surface: Mark;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
@theme {
|
||||||
|
--palette-white: oklch(1 0 0);
|
||||||
|
--palette-slate-50: oklch(0.985 0.003 247);
|
||||||
|
--palette-slate-100: oklch(0.94 0.01 247);
|
||||||
|
--palette-slate-300: oklch(0.87 0.015 247);
|
||||||
|
--palette-slate-500: oklch(0.48 0.025 247);
|
||||||
|
--palette-slate-800: oklch(0.25 0.025 247);
|
||||||
|
--palette-slate-950: oklch(0.16 0.02 255);
|
||||||
|
--palette-blue-500: oklch(0.7 0.14 250);
|
||||||
|
--palette-blue-600: oklch(0.55 0.18 255);
|
||||||
|
--palette-blue-700: oklch(0.48 0.2 255);
|
||||||
|
--palette-red-500: oklch(0.68 0.19 25);
|
||||||
|
--palette-red-600: oklch(0.55 0.2 25);
|
||||||
|
--palette-red-700: oklch(0.47 0.2 25);
|
||||||
|
|
||||||
|
--space-1: 0.25rem;
|
||||||
|
--space-2: 0.5rem;
|
||||||
|
--space-3: 0.75rem;
|
||||||
|
--space-4: 1rem;
|
||||||
|
--space-5: 1.25rem;
|
||||||
|
--space-6: 1.5rem;
|
||||||
|
--space-8: 2rem;
|
||||||
|
--space-12: 3rem;
|
||||||
|
|
||||||
|
--font-size-xs: 0.75rem;
|
||||||
|
--font-size-sm: 0.875rem;
|
||||||
|
--font-size-md: 1rem;
|
||||||
|
--font-size-lg: 1.125rem;
|
||||||
|
--line-height-tight: 1.25;
|
||||||
|
--line-height-normal: 1.5;
|
||||||
|
--line-height-relaxed: 1.7;
|
||||||
|
--font-weight-regular: 400;
|
||||||
|
--font-weight-semibold: 650;
|
||||||
|
--font-weight-bold: 750;
|
||||||
|
|
||||||
|
--radius-xs: 0.25rem;
|
||||||
|
--radius-sm: 0.5rem;
|
||||||
|
--radius-md: 0.75rem;
|
||||||
|
--radius-full: 999px;
|
||||||
|
|
||||||
|
--shadow-panel: 0 8px 28px rgb(15 23 42 / 8%);
|
||||||
|
--shadow-popover: 0 14px 40px rgb(15 23 42 / 16%);
|
||||||
|
--shadow-dialog: 0 24px 70px rgb(15 23 42 / 25%);
|
||||||
|
|
||||||
|
--duration-fast: 100ms;
|
||||||
|
--duration-normal: 180ms;
|
||||||
|
--duration-slow: 300ms;
|
||||||
|
--easing-standard: cubic-bezier(0.2, 0, 0, 1);
|
||||||
|
--easing-emphasized: cubic-bezier(0.2, 0, 0, 1.2);
|
||||||
|
|
||||||
|
--size-control-sm: 2.25rem;
|
||||||
|
--size-control-md: 2.75rem;
|
||||||
|
--size-touch-target: 2.75rem;
|
||||||
|
--size-icon-sm: 1rem;
|
||||||
|
--size-icon-md: 1.25rem;
|
||||||
|
--size-icon-lg: 1.5rem;
|
||||||
|
--icon-stroke-default: 2;
|
||||||
|
|
||||||
|
--breakpoint-compact: 48rem;
|
||||||
|
--breakpoint-medium: 64rem;
|
||||||
|
--breakpoint-wide: 80rem;
|
||||||
|
--container-content: 72rem;
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
@theme {
|
||||||
|
--color-surface: var(--palette-slate-50);
|
||||||
|
--color-surface-muted: var(--palette-slate-100);
|
||||||
|
--color-panel: var(--palette-white);
|
||||||
|
--color-surface-elevated: var(--palette-white);
|
||||||
|
--color-border: var(--palette-slate-300);
|
||||||
|
--color-border-strong: var(--palette-slate-500);
|
||||||
|
--color-content: var(--palette-slate-800);
|
||||||
|
--color-content-muted: var(--palette-slate-500);
|
||||||
|
--color-content-inverse: var(--palette-white);
|
||||||
|
--color-action: var(--palette-blue-600);
|
||||||
|
--color-action-hover: var(--palette-blue-700);
|
||||||
|
--color-action-pressed: var(--palette-blue-700);
|
||||||
|
--color-danger: var(--palette-red-600);
|
||||||
|
--color-danger-hover: var(--palette-red-700);
|
||||||
|
--color-on-action: var(--palette-white);
|
||||||
|
--color-focus: oklch(0.72 0.16 225);
|
||||||
|
--color-disabled-content: color-mix(in oklch, var(--color-content) 55%, transparent);
|
||||||
|
--color-disabled-surface: var(--color-surface-muted);
|
||||||
|
--color-info-content: oklch(0.38 0.16 255);
|
||||||
|
--color-info-surface: oklch(0.95 0.03 255);
|
||||||
|
--color-info-border: oklch(0.75 0.08 250);
|
||||||
|
--color-success-content: oklch(0.35 0.12 155);
|
||||||
|
--color-success-surface: oklch(0.95 0.04 155);
|
||||||
|
--color-success-border: oklch(0.72 0.1 155);
|
||||||
|
--color-warning-content: oklch(0.38 0.12 70);
|
||||||
|
--color-warning-surface: oklch(0.96 0.05 80);
|
||||||
|
--color-warning-border: oklch(0.75 0.12 80);
|
||||||
|
--color-danger-content: oklch(0.42 0.18 25);
|
||||||
|
--color-danger-surface: oklch(0.96 0.035 25);
|
||||||
|
--color-danger-border: oklch(0.72 0.12 25);
|
||||||
|
|
||||||
|
--font-sans: Inter, ui-sans-serif, system-ui, sans-serif;
|
||||||
|
--spacing-page: var(--space-6);
|
||||||
|
--radius-control: var(--radius-sm);
|
||||||
|
--radius-surface: var(--radius-md);
|
||||||
|
--radius-modal: var(--radius-md);
|
||||||
|
--elevation-panel: var(--shadow-panel);
|
||||||
|
--elevation-popover: var(--shadow-popover);
|
||||||
|
--elevation-dialog: var(--shadow-dialog);
|
||||||
|
--layer-base: 0;
|
||||||
|
--layer-sticky: 30;
|
||||||
|
--layer-navigation: 50;
|
||||||
|
--layer-popover: 60;
|
||||||
|
--layer-modal: 70;
|
||||||
|
--layer-toast: 80;
|
||||||
|
--opacity-disabled: 0.55;
|
||||||
|
--opacity-scrim: 0.55;
|
||||||
|
--opacity-skeleton: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-theme="dark"] {
|
||||||
|
--color-surface: var(--palette-slate-950);
|
||||||
|
--color-surface-muted: oklch(0.25 0.025 255);
|
||||||
|
--color-panel: oklch(0.205 0.022 255);
|
||||||
|
--color-surface-elevated: oklch(0.235 0.025 255);
|
||||||
|
--color-border: oklch(0.36 0.025 255);
|
||||||
|
--color-border-strong: oklch(0.58 0.025 255);
|
||||||
|
--color-content: oklch(0.94 0.012 255);
|
||||||
|
--color-content-muted: oklch(0.74 0.025 255);
|
||||||
|
--color-content-inverse: var(--palette-slate-950);
|
||||||
|
--color-action: var(--palette-blue-500);
|
||||||
|
--color-action-hover: oklch(0.79 0.12 245);
|
||||||
|
--color-action-pressed: oklch(0.83 0.1 245);
|
||||||
|
--color-danger: var(--palette-red-500);
|
||||||
|
--color-danger-hover: oklch(0.76 0.16 25);
|
||||||
|
--color-on-action: var(--palette-slate-950);
|
||||||
|
--color-focus: oklch(0.82 0.15 220);
|
||||||
|
--color-disabled-content: color-mix(in oklch, var(--color-content) 55%, transparent);
|
||||||
|
--color-disabled-surface: var(--color-surface-muted);
|
||||||
|
--color-info-content: oklch(0.83 0.09 250);
|
||||||
|
--color-info-surface: oklch(0.27 0.045 255);
|
||||||
|
--color-info-border: oklch(0.55 0.09 250);
|
||||||
|
--color-success-content: oklch(0.83 0.1 155);
|
||||||
|
--color-success-surface: oklch(0.27 0.045 155);
|
||||||
|
--color-success-border: oklch(0.53 0.1 155);
|
||||||
|
--color-warning-content: oklch(0.88 0.1 80);
|
||||||
|
--color-warning-surface: oklch(0.29 0.045 80);
|
||||||
|
--color-warning-border: oklch(0.58 0.11 80);
|
||||||
|
--color-danger-content: oklch(0.84 0.11 25);
|
||||||
|
--color-danger-surface: oklch(0.28 0.055 25);
|
||||||
|
--color-danger-border: oklch(0.56 0.13 25);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
export const REQUIRED_PRIMITIVE_TOKENS = Object.freeze([
|
||||||
|
"--space-1",
|
||||||
|
"--space-2",
|
||||||
|
"--space-4",
|
||||||
|
"--font-size-sm",
|
||||||
|
"--line-height-normal",
|
||||||
|
"--radius-sm",
|
||||||
|
"--shadow-dialog",
|
||||||
|
"--duration-fast",
|
||||||
|
"--easing-standard",
|
||||||
|
"--size-control-md",
|
||||||
|
"--size-touch-target",
|
||||||
|
"--size-icon-md",
|
||||||
|
"--breakpoint-compact",
|
||||||
|
] as const);
|
||||||
|
|
||||||
|
export const REQUIRED_SEMANTIC_TOKENS = Object.freeze([
|
||||||
|
"--color-surface",
|
||||||
|
"--color-surface-muted",
|
||||||
|
"--color-surface-elevated",
|
||||||
|
"--color-content",
|
||||||
|
"--color-content-muted",
|
||||||
|
"--color-content-inverse",
|
||||||
|
"--color-border",
|
||||||
|
"--color-border-strong",
|
||||||
|
"--color-action",
|
||||||
|
"--color-action-hover",
|
||||||
|
"--color-action-pressed",
|
||||||
|
"--color-danger",
|
||||||
|
"--color-warning-content",
|
||||||
|
"--color-success-content",
|
||||||
|
"--color-info-content",
|
||||||
|
"--color-focus",
|
||||||
|
"--color-disabled-content",
|
||||||
|
"--color-disabled-surface",
|
||||||
|
"--elevation-panel",
|
||||||
|
"--layer-navigation",
|
||||||
|
"--layer-popover",
|
||||||
|
"--layer-modal",
|
||||||
|
"--layer-toast",
|
||||||
|
"--opacity-disabled",
|
||||||
|
"--opacity-scrim",
|
||||||
|
"--opacity-skeleton",
|
||||||
|
] as const);
|
||||||
|
|
||||||
|
export const REQUIRED_COMPONENT_TOKENS = Object.freeze([
|
||||||
|
"--button-primary-background",
|
||||||
|
"--button-primary-content",
|
||||||
|
"--button-primary-hover",
|
||||||
|
"--field-border",
|
||||||
|
"--field-border-invalid",
|
||||||
|
"--dialog-elevation",
|
||||||
|
"--navigation-active-background",
|
||||||
|
"--drawer-width",
|
||||||
|
"--toast-width",
|
||||||
|
] as const);
|
||||||
|
|
||||||
|
export const DESIGN_TOKEN_CONTRACT = Object.freeze({
|
||||||
|
primitive: REQUIRED_PRIMITIVE_TOKENS,
|
||||||
|
semantic: REQUIRED_SEMANTIC_TOKENS,
|
||||||
|
component: REQUIRED_COMPONENT_TOKENS,
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useLocation } from "react-router-dom";
|
import { useLocation } from "react-router-dom";
|
||||||
|
|
||||||
import { PageHeader } from "../components/page-header.jsx";
|
import { PageHeader } from "../design-system/index.js";
|
||||||
import { useSession } from "../providers/session-provider.jsx";
|
import { useSession } from "../providers/session-provider.jsx";
|
||||||
|
|
||||||
export default function AuthExamplePage() {
|
export default function AuthExamplePage() {
|
||||||
|
|||||||
@@ -7,15 +7,13 @@ import {
|
|||||||
EmptySurface,
|
EmptySurface,
|
||||||
LoadingSurface,
|
LoadingSurface,
|
||||||
TerminalErrorSurface,
|
TerminalErrorSurface,
|
||||||
} from "../components/async-surface.jsx";
|
|
||||||
import { PageHeader } from "../components/page-header.jsx";
|
|
||||||
import {
|
|
||||||
AuthRequiredSurface,
|
AuthRequiredSurface,
|
||||||
ForbiddenSurface,
|
ForbiddenSurface,
|
||||||
NotFoundSurface,
|
NotFoundSurface,
|
||||||
} from "../components/state-surfaces.jsx";
|
Button,
|
||||||
import { Button } from "../components/ui/button.jsx";
|
Card,
|
||||||
import { Card } from "../components/ui/card.jsx";
|
PageHeader,
|
||||||
|
} from "../design-system/index.js";
|
||||||
|
|
||||||
export default function StateGalleryPage() {
|
export default function StateGalleryPage() {
|
||||||
const [lastAction, setLastAction] = useState(
|
const [lastAction, setLastAction] = useState(
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user