dealsystem 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +64 -2
  2. package/dist/api/errors.d.ts +25 -0
  3. package/dist/api/errors.js +38 -0
  4. package/dist/api/http.d.ts +56 -0
  5. package/dist/api/http.js +406 -0
  6. package/dist/api/legal.d.ts +9 -0
  7. package/dist/api/legal.js +20 -0
  8. package/dist/api/oauth.d.ts +35 -0
  9. package/dist/api/oauth.js +113 -0
  10. package/dist/api/types.d.ts +142 -0
  11. package/dist/api/types.js +9 -0
  12. package/dist/auth/credentials.d.ts +28 -0
  13. package/dist/auth/credentials.js +96 -0
  14. package/dist/auth/session.d.ts +10 -0
  15. package/dist/auth/session.js +46 -0
  16. package/dist/bin.d.ts +2 -0
  17. package/dist/bin.js +4 -0
  18. package/dist/check/allowlist.d.ts +9 -0
  19. package/dist/check/allowlist.js +74 -0
  20. package/dist/check/catalog.d.ts +6 -0
  21. package/dist/check/catalog.js +410 -0
  22. package/dist/check/context.d.ts +79 -0
  23. package/dist/check/context.js +230 -0
  24. package/dist/check/fileset.d.ts +19 -0
  25. package/dist/check/fileset.js +91 -0
  26. package/dist/check/format.d.ts +25 -0
  27. package/dist/check/format.js +79 -0
  28. package/dist/check/index.d.ts +8 -0
  29. package/dist/check/index.js +9 -0
  30. package/dist/check/rule.d.ts +15 -0
  31. package/dist/check/rule.js +6 -0
  32. package/dist/check/rules/a11y.d.ts +3 -0
  33. package/dist/check/rules/a11y.js +433 -0
  34. package/dist/check/rules/privacy.d.ts +9 -0
  35. package/dist/check/rules/privacy.js +437 -0
  36. package/dist/check/rules/quality.d.ts +11 -0
  37. package/dist/check/rules/quality.js +451 -0
  38. package/dist/check/rules/schedule.d.ts +2 -0
  39. package/dist/check/rules/schedule.js +30 -0
  40. package/dist/check/rules/security.d.ts +18 -0
  41. package/dist/check/rules/security.js +744 -0
  42. package/dist/check/rules/structure.d.ts +2 -0
  43. package/dist/check/rules/structure.js +399 -0
  44. package/dist/check/run.d.ts +15 -0
  45. package/dist/check/run.js +147 -0
  46. package/dist/check/sdk.d.ts +56 -0
  47. package/dist/check/sdk.js +58 -0
  48. package/dist/check/types.d.ts +116 -0
  49. package/dist/check/types.js +2 -0
  50. package/dist/check/util/code.d.ts +19 -0
  51. package/dist/check/util/code.js +113 -0
  52. package/dist/check/util/color.d.ts +10 -0
  53. package/dist/check/util/color.js +53 -0
  54. package/dist/check/util/csp.d.ts +71 -0
  55. package/dist/check/util/csp.js +229 -0
  56. package/dist/check/util/html.d.ts +31 -0
  57. package/dist/check/util/html.js +65 -0
  58. package/dist/check/util/lines.d.ts +1 -0
  59. package/dist/check/util/lines.js +2 -0
  60. package/dist/check/util/literal.d.ts +1 -0
  61. package/dist/check/util/literal.js +3 -0
  62. package/dist/check/util/svelte.d.ts +42 -0
  63. package/dist/check/util/svelte.js +109 -0
  64. package/dist/cli/context.d.ts +40 -0
  65. package/dist/cli/context.js +107 -0
  66. package/dist/cli/io.d.ts +26 -0
  67. package/dist/cli/io.js +68 -0
  68. package/dist/cli/main.d.ts +24 -0
  69. package/dist/cli/main.js +269 -0
  70. package/dist/commands/check.d.ts +4 -0
  71. package/dist/commands/check.js +54 -0
  72. package/dist/commands/deploy.d.ts +20 -0
  73. package/dist/commands/deploy.js +315 -0
  74. package/dist/commands/dev.d.ts +29 -0
  75. package/dist/commands/dev.js +149 -0
  76. package/dist/commands/image.d.ts +12 -0
  77. package/dist/commands/image.js +291 -0
  78. package/dist/commands/login.d.ts +3 -0
  79. package/dist/commands/login.js +116 -0
  80. package/dist/commands/pull.d.ts +12 -0
  81. package/dist/commands/pull.js +178 -0
  82. package/dist/commands/site.d.ts +9 -0
  83. package/dist/commands/site.js +84 -0
  84. package/dist/commands/sync.d.ts +2 -0
  85. package/dist/commands/sync.js +126 -0
  86. package/dist/index.d.ts +10 -0
  87. package/dist/index.js +10 -0
  88. package/dist/project/agentFiles.d.ts +17 -0
  89. package/dist/project/agentFiles.js +156 -0
  90. package/dist/project/agentsBlock.d.ts +2 -0
  91. package/dist/project/agentsBlock.js +14 -0
  92. package/dist/project/siteConfig.d.ts +5 -0
  93. package/dist/project/siteConfig.js +35 -0
  94. package/dist/project/snapshot.d.ts +21 -0
  95. package/dist/project/snapshot.js +125 -0
  96. package/dist/project/svelteConfig.d.ts +4 -0
  97. package/dist/project/svelteConfig.js +74 -0
  98. package/dist/project/tar.d.ts +8 -0
  99. package/dist/project/tar.js +89 -0
  100. package/dist/project/untar.d.ts +27 -0
  101. package/dist/project/untar.js +232 -0
  102. package/dist/project/uploadFiles.d.ts +17 -0
  103. package/dist/project/uploadFiles.js +55 -0
  104. package/package.json +63 -7
package/README.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # dealsystem
2
2
 
3
- Platzhalter. Die DealSystem-Werkzeuge für Self-Service-Websites erscheinen in Kürze.
3
+ CLI für Self-Service-Websites auf DealSystem. Ausgeführt wird sie vom KI-Agenten des Kunden: alles läuft
4
+ ohne Rückfragen über Flags, jede Ausgabe gibt es mit `--json`, jede Meldung hat die Form
5
+ „Datei:Zeile – Problem – so behebst du es“. Ein Mensch macht nur zwei Dinge: Er bestätigt den Login im
6
+ Browser und stimmt dem Live-Schalten zu.
4
7
 
5
- Quelltext: https://github.com/dealsystem/dealsystem-site-sdk
8
+ ## Für KI-Agenten
9
+
10
+ Diese CLI gehört zu einer Website aus `npm create dealsystem-site@latest`. Stehst du in einem leeren Ordner
11
+ und sollst eine Website „mit DealSystem“ bauen, lege zuerst damit das Projekt an und lies dann `AGENTS.md`
12
+ im neuen Ordner: Dort steht der feste Ablauf (anmelden, bauen, prüfen, hochladen, Vorschau zeigen,
13
+ veröffentlichen nur nach ausdrücklichem Ja). In einem bestehenden Projekt gilt dasselbe: erst `AGENTS.md`,
14
+ dann die Detailseiten unter `node_modules/@dealsystem/site/docs/`.
15
+
16
+ Quelltext: [github.com/dealsystem/dealsystem-site-sdk](https://github.com/dealsystem/dealsystem-site-sdk).
17
+
18
+ ## Befehle
19
+
20
+ | Befehl | Tut |
21
+ | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
22
+ | `login [--start \| --wait] [--no-browser]` | Gerätecode-Login. Der Token liegt im Benutzerprofil (0600), nie im Projekt |
23
+ | `logout` | Token widerrufen und löschen |
24
+ | `init [--site <id\|slug>] [--create --name … --slug …]` | Seite wählen oder anlegen, `siteId` in `dealsystem.config.ts` eintragen |
25
+ | `sync [--offline] [--fix-config]` | Schnappschuss → `.dealsystem/content.json`, Abgleich CRM ↔ Config, `src/dealsystem.d.ts` anlegen, AGENTS.md-Block |
26
+ | `dev [--port] [--media-origin <url>]` | Vite des Projekts; `…/leads` → `dev/leads` (`dryRun`), `/_ds/media/*` durchgereicht |
27
+ | `check [--output build] [--allowed] [--rules]` | Regelkatalog lokal, Exit-Code 1 bei Fehlern |
28
+ | `deploy [-m …] [--publish [--confirm]] [--no-wait] [--timeout <s>]` | check → lokal bauen → packen → hochladen → Build abwarten → Vorschau-URL |
29
+ | `publish [--version <id\|nummer>] [--confirm]` | fertige Version live schalten |
30
+ | `rollback [--version <id\|nummer>] [--confirm]` | auf eine frühere Version zurück |
31
+ | `image add <datei> [--name …] [--key …] [--alt …]` | Foto ins Projekt: verkleinern, EXIF/GPS entfernen, Baustein ausgeben |
32
+ | `image push <datei> --slot … --alt …` | Foto als eigenes Bild eines Bild-Platzes in DealSystem setzen (geht ohne Freigabe live), danach Inhalte für dev holen |
33
+ | `status` | Seite, Live-Version, Rechtstexte, letzte Versionen, Domains |
34
+
35
+ Allgemein: `--json`, `--dir <ordner>`, `--site <id>`, `--api-url <url>` (oder `DEALSYSTEM_API_URL`),
36
+ `--quiet`. Für eigene CI: API-Schlüssel in `DEALSYSTEM_TOKEN`.
37
+
38
+ Exit-Codes: `0` ok · `1` Prüfung oder Build fehlgeschlagen · `2` falscher Aufruf oder Bestätigung nötig ·
39
+ `3` nicht angemeldet · `4` API nicht erreichbar.
40
+
41
+ **Live schalten:** `deploy --publish` und `publish`/`rollback` fragen am Terminal nach. Ohne Terminal
42
+ (Agent) brechen sie mit Exit-Code 2 und `confirmation_required` ab. Der Agent fragt dann den Nutzer und
43
+ wiederholt den Befehl mit `--confirm`.
44
+
45
+ ## Regelkatalog als Bibliothek
46
+
47
+ Der Build-Host ruft dieselben Regeln auf. Sie laufen ohne Netz und ohne Browser und führen nichts aus dem
48
+ Projekt aus: Konfigurationen werden statisch gelesen.
49
+
50
+ ```ts
51
+ import { runCheck, toBuildReportCheck, RULE_SET_VERSION } from 'dealsystem/check';
52
+
53
+ const source = await runCheck({
54
+ projectDir: '/job/src',
55
+ stages: ['source'],
56
+ sdkRange: job.sdkRange,
57
+ ruleSetVersion: job.ruleSetVersion,
58
+ });
59
+ const output = await runCheck({
60
+ outputDir: '/job/build',
61
+ stages: ['output'],
62
+ siteUrl: job.env.PUBLIC_DEALSYSTEM_SITE_URL,
63
+ });
64
+ const check = toBuildReportCheck([source, output]); // → report.check
65
+ ```
66
+
67
+ Phase 2 (axe-core, Lighthouse) dockt über `plugins: CheckPlugin[]` an.
@@ -0,0 +1,25 @@
1
+ export declare const EXIT: {
2
+ readonly ok: 0;
3
+ /** Prüfung oder Build mit Fehlern. */
4
+ readonly failed: 1;
5
+ /** Falscher Aufruf oder fehlende Bestätigung. */
6
+ readonly usage: 2;
7
+ /** Nicht angemeldet oder Anmeldung abgelaufen. */
8
+ readonly auth: 3;
9
+ /** API oder Netz nicht erreichbar, unerwartete Antwort. */
10
+ readonly api: 4;
11
+ };
12
+ export type ExitCode = (typeof EXIT)[keyof typeof EXIT];
13
+ export declare class CliError extends Error {
14
+ readonly code: string;
15
+ readonly fix: string;
16
+ readonly exitCode: ExitCode;
17
+ readonly data?: unknown | undefined;
18
+ constructor(code: string, message: string, fix: string, exitCode?: ExitCode, data?: unknown | undefined);
19
+ }
20
+ /** Fehlerantwort der API v1: `{ error, message, status, code }`. */
21
+ export declare class ApiError extends CliError {
22
+ readonly status: number;
23
+ constructor(status: number, apiCode: string, message: string, fix: string);
24
+ }
25
+ export declare function notLoggedIn(): CliError;
@@ -0,0 +1,38 @@
1
+ // Fehler der CLI mit Code, Text und Korrektur-Anweisung. Exit-Codes sind Teil des Vertrags mit dem Agenten.
2
+ export const EXIT = {
3
+ ok: 0,
4
+ /** Prüfung oder Build mit Fehlern. */
5
+ failed: 1,
6
+ /** Falscher Aufruf oder fehlende Bestätigung. */
7
+ usage: 2,
8
+ /** Nicht angemeldet oder Anmeldung abgelaufen. */
9
+ auth: 3,
10
+ /** API oder Netz nicht erreichbar, unerwartete Antwort. */
11
+ api: 4,
12
+ };
13
+ export class CliError extends Error {
14
+ code;
15
+ fix;
16
+ exitCode;
17
+ data;
18
+ constructor(code, message, fix, exitCode = EXIT.failed, data) {
19
+ super(message);
20
+ this.code = code;
21
+ this.fix = fix;
22
+ this.exitCode = exitCode;
23
+ this.data = data;
24
+ this.name = 'CliError';
25
+ }
26
+ }
27
+ /** Fehlerantwort der API v1: `{ error, message, status, code }`. */
28
+ export class ApiError extends CliError {
29
+ status;
30
+ constructor(status, apiCode, message, fix) {
31
+ super(apiCode, message, fix, status === 401 ? EXIT.auth : EXIT.api);
32
+ this.status = status;
33
+ this.name = 'ApiError';
34
+ }
35
+ }
36
+ export function notLoggedIn() {
37
+ return new CliError('not_logged_in', 'Du bist nicht angemeldet.', 'Führe `npx dealsystem login` aus und bestätige die Anmeldung im Browser.', EXIT.auth);
38
+ }
@@ -0,0 +1,56 @@
1
+ import type { DeployApi, PreparedUpload, PreparedImageUpload, ReleaseResult, SourceDownload, Version, VersionSummary, Website, WebsiteDetails, WebsiteSlot } from './types.js';
2
+ export interface TokenProvider {
3
+ getToken(): Promise<string>;
4
+ /** Erneuert den Token nach einer 401. `null`, wenn das nicht geht (z. B. API-Schlüssel aus der Umgebung). */
5
+ refresh(): Promise<string | null>;
6
+ }
7
+ export type FetchLike = typeof fetch;
8
+ /** Was zu tun ist, wenn Rechtstexte oder Firmendaten fehlen (Server-Fehler und Vorprüfung in `publish`). */
9
+ export declare const LEGAL_PROFILE_FIX = "Bitte den Inhaber, im CRM unter \u201EEigene Website \u2192 Rechtliches\u201C die fehlenden Angaben einzutragen: Impressum, Datenschutzerkl\u00E4rung, Firmenname und E-Mail-Adresse. Diese Texte schreibt er selbst. Danach `npx dealsystem sync`, neu hochladen, die neue Vorschau zeigen und neu fragen.";
10
+ export declare function normalizeWebsite(raw: unknown): Website;
11
+ export declare function normalizeVersionSummary(raw: unknown): VersionSummary;
12
+ export declare function normalizeVersion(raw: unknown): Version;
13
+ export declare class HttpDeployApi implements DeployApi {
14
+ private readonly tokens;
15
+ private readonly fetchImpl;
16
+ private readonly base;
17
+ constructor(apiUrl: string, tokens: TokenProvider, fetchImpl?: FetchLike);
18
+ private request;
19
+ private call;
20
+ listWebsites(): Promise<Website[]>;
21
+ createWebsite(input: {
22
+ name: string;
23
+ slug: string;
24
+ }): Promise<Website>;
25
+ getWebsite(id: string): Promise<WebsiteDetails>;
26
+ getContent(id: string): Promise<unknown>;
27
+ listVersions(id: string, limit?: number): Promise<VersionSummary[]>;
28
+ prepareUpload(id: string, input: {
29
+ sha256: string;
30
+ bytes: number;
31
+ message?: string;
32
+ }): Promise<PreparedUpload>;
33
+ uploadSource(upload: PreparedUpload, body: Uint8Array): Promise<void>;
34
+ completeUpload(id: string, versionId: string): Promise<Version>;
35
+ getVersion(id: string, versionId: string): Promise<Version>;
36
+ /** Antwort `{ site, release }`; `release` ist `null`, wenn die Version schon live war. */
37
+ private release;
38
+ publish(id: string, versionId: string): Promise<ReleaseResult>;
39
+ rollback(id: string, versionId?: string): Promise<ReleaseResult>;
40
+ listSlots(id: string): Promise<WebsiteSlot[]>;
41
+ prepareImageUpload(id: string, input: {
42
+ slotKey: string;
43
+ bytes: number;
44
+ }): Promise<PreparedImageUpload>;
45
+ uploadImage(upload: PreparedImageUpload, body: Uint8Array): Promise<void>;
46
+ completeImageUpload(id: string, uploadId: string, input: {
47
+ slotKey: string;
48
+ alt: string;
49
+ }): Promise<WebsiteSlot | null>;
50
+ getSourceDownload(id: string, versionId: string): Promise<SourceDownload>;
51
+ downloadSource(source: SourceDownload, maxBytes: number): Promise<Uint8Array>;
52
+ devLead(id: string, body: unknown): Promise<{
53
+ status: number;
54
+ body: unknown;
55
+ }>;
56
+ }
@@ -0,0 +1,406 @@
1
+ // Dünne HTTP-Schicht für `/api/v1/websites/…`. Normalisiert Antworten defensiv, damit kleine Abweichungen
2
+ // im Core (zusätzliche Felder, fehlende optionale Felder) die CLI nicht brechen.
3
+ import { ApiError, CliError, EXIT } from './errors.js';
4
+ const str = (v) => (typeof v === 'string' ? v : null);
5
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
6
+ const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
7
+ const arr = (v) => (Array.isArray(v) ? v : []);
8
+ function parseJson(text) {
9
+ if (!text)
10
+ return null;
11
+ try {
12
+ return JSON.parse(text);
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ /** Was zu tun ist, wenn Rechtstexte oder Firmendaten fehlen (Server-Fehler und Vorprüfung in `publish`). */
19
+ export const LEGAL_PROFILE_FIX = 'Bitte den Inhaber, im CRM unter „Eigene Website → Rechtliches“ die fehlenden Angaben einzutragen: Impressum, Datenschutzerklärung, Firmenname und E-Mail-Adresse. Diese Texte schreibt er selbst. Danach `npx dealsystem sync`, neu hochladen, die neue Vorschau zeigen und neu fragen.';
20
+ /** Korrektur-Anweisungen für bekannte Fehlercodes der API. */
21
+ const FIXES = {
22
+ legal_profile_incomplete: LEGAL_PROFILE_FIX,
23
+ plan_limit_reached: 'Das Limit des Abos ist erreicht. Bitte den Inhaber, das Abo zu erweitern, oder lösche alte Seiten.',
24
+ app_disabled: 'Die App „Eigene Website“ ist im Workspace nicht freigeschaltet. Bitte den Inhaber, sie freizuschalten.',
25
+ forbidden: 'Dir fehlt das Recht dafür. Bitte einen Admin des Workspaces, es dir zu geben.',
26
+ plan_limit: 'Das Limit des Abos ist erreicht. Bitte den Inhaber, das Abo zu erweitern, oder lösche alte Versionen bzw. Seiten.',
27
+ user_bound_key_required: 'Live schalten braucht einen Menschen: melde dich mit `npx dealsystem login` an statt mit einem API-Schlüssel ohne Nutzer.',
28
+ live_changed: 'Jemand hat gerade eine andere Version live geschaltet. Prüfe mit `npx dealsystem status` und versuche es erneut.',
29
+ upload_missing: 'Das Archiv ist nicht angekommen. Führe `npx dealsystem deploy` erneut aus.',
30
+ upload_size_mismatch: 'Das Archiv kam unvollständig an. Führe `npx dealsystem deploy` erneut aus.',
31
+ insufficient_scope: 'Die Anmeldung reicht dafür nicht. Führe `npx dealsystem login` erneut aus.',
32
+ not_found: 'Prüfe die `siteId` in dealsystem.config.ts oder führe `npx dealsystem init` aus.',
33
+ version_not_ready: 'Die Version ist noch nicht fertig gebaut. Warte mit `npx dealsystem status`, bis sie `ready` ist.',
34
+ invalid_token: 'Führe `npx dealsystem login` aus.',
35
+ source_not_uploaded: 'Diese Version wurde nie vollständig hochgeladen. Wähle eine andere mit `--version <nummer>` (Liste: `npx dealsystem status --site <id>`).',
36
+ source_expired: 'Der Quellcode dieser Version ist nach der Aufbewahrungsfrist gelöscht. Nimm die Live-Version (ohne `--version`) oder eine neuere.',
37
+ source_unavailable: 'Der Quellcode dieser Version ist nicht mehr vorhanden. Nimm die Live-Version (ohne `--version`) oder eine neuere.',
38
+ rate_limited: 'Zu viele Abrufe in kurzer Zeit. Warte eine Minute und versuche es erneut.',
39
+ slot_not_found: 'Diesen Bild-Platz kennt DealSystem nicht. Die Schlüssel stehen im Code als <MediaImage key="…">; ein neuer Platz ist erst nach `npx dealsystem deploy` bekannt.',
40
+ type_changed: 'Dieser Platz ist kein Bild-Platz. Nimm den Schlüssel eines <MediaImage key="…">.',
41
+ missing_alt: 'Gib mit `--alt "…"` an, was auf dem Bild zu sehen ist.',
42
+ unsupported_type: 'Erlaubt sind JPEG, PNG und WebP.',
43
+ too_many_pixels: 'Das Bild hat zu viele Pixel. Verkleinere es und versuche es erneut.',
44
+ storage_unavailable: 'Bilder lassen sich gerade nicht speichern. Versuche es später erneut.',
45
+ };
46
+ function fixFor(status, code) {
47
+ if (FIXES[code])
48
+ return FIXES[code];
49
+ if (status === 401)
50
+ return FIXES.invalid_token;
51
+ if (status === 403)
52
+ return FIXES.forbidden;
53
+ if (status === 404)
54
+ return FIXES.not_found;
55
+ if (status === 429)
56
+ return 'Zu viele Anfragen. Warte eine Minute und versuche es erneut.';
57
+ if (status >= 500)
58
+ return 'Der DealSystem-Server hat ein Problem. Versuche es in ein paar Minuten erneut.';
59
+ return 'Prüfe die Eingaben und versuche es erneut.';
60
+ }
61
+ export function normalizeWebsite(raw) {
62
+ const o = obj(raw);
63
+ return {
64
+ id: str(o.id) ?? '',
65
+ name: str(o.name) ?? '',
66
+ slug: str(o.slug) ?? '',
67
+ status: str(o.status) ?? 'active',
68
+ liveVersionId: str(o.liveVersionId),
69
+ defaultHost: str(o.defaultHost),
70
+ primaryHost: str(o.primaryHost),
71
+ };
72
+ }
73
+ function normalizeFinding(raw) {
74
+ const o = obj(raw);
75
+ const rule = str(o.rule);
76
+ const message = str(o.message);
77
+ if (!rule || !message)
78
+ return null;
79
+ return { rule, file: str(o.file), line: num(o.line), message, fix: str(o.fix) };
80
+ }
81
+ function normalizeCheck(raw) {
82
+ if (!raw || typeof raw !== 'object')
83
+ return null;
84
+ const o = obj(raw);
85
+ const errors = arr(o.errors)
86
+ .map(normalizeFinding)
87
+ .filter((f) => f !== null);
88
+ return {
89
+ passed: errors.length === 0,
90
+ ruleSetVersion: str(o.ruleSetVersion) ?? '',
91
+ errors,
92
+ warnings: arr(o.warnings)
93
+ .map(normalizeFinding)
94
+ .filter((f) => f !== null),
95
+ };
96
+ }
97
+ export function normalizeVersionSummary(raw) {
98
+ const o = obj(raw);
99
+ return {
100
+ id: str(o.id) ?? str(o.versionId) ?? '',
101
+ number: num(o.number) ?? 0,
102
+ status: str(o.status) ?? 'unknown',
103
+ trigger: str(o.trigger) ?? 'upload',
104
+ message: str(o.message),
105
+ createdAt: str(o.createdAt),
106
+ previewUrl: str(o.previewUrl),
107
+ };
108
+ }
109
+ export function normalizeVersion(raw) {
110
+ const o = obj(raw);
111
+ return {
112
+ ...normalizeVersionSummary(raw),
113
+ checkResult: normalizeCheck(o.checkResult),
114
+ logExcerpt: str(o.logExcerpt) ?? str(o.log),
115
+ };
116
+ }
117
+ function normalizeDomain(raw) {
118
+ const o = obj(raw);
119
+ return {
120
+ host: str(o.host) ?? '',
121
+ kind: str(o.kind) ?? 'primary',
122
+ active: o.active === true || str(o.activatedAt) !== null,
123
+ };
124
+ }
125
+ function normalizeSlot(raw) {
126
+ const o = obj(raw);
127
+ const value = obj(o.value);
128
+ return {
129
+ key: str(o.key) ?? '',
130
+ type: str(o.type) ?? 'text',
131
+ label: str(o.label) ?? str(o.key) ?? '',
132
+ inUse: o.inUse !== false,
133
+ overridden: o.overridden === true,
134
+ mediaId: str(value.mediaId),
135
+ };
136
+ }
137
+ export class HttpDeployApi {
138
+ tokens;
139
+ fetchImpl;
140
+ base;
141
+ constructor(apiUrl, tokens, fetchImpl = fetch) {
142
+ this.tokens = tokens;
143
+ this.fetchImpl = fetchImpl;
144
+ this.base = apiUrl.replace(/\/+$/, '');
145
+ }
146
+ async request(method, path, body) {
147
+ const send = async (token) => {
148
+ try {
149
+ return await this.fetchImpl(`${this.base}/api/v1${path}`, {
150
+ method,
151
+ headers: {
152
+ Authorization: `Bearer ${token}`,
153
+ Accept: 'application/json',
154
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
155
+ },
156
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
157
+ });
158
+ }
159
+ catch (e) {
160
+ throw new CliError('network_error', `${this.base} ist nicht erreichbar (${e.message}).`, 'Prüfe die Internetverbindung und versuche es erneut.', EXIT.api);
161
+ }
162
+ };
163
+ let res = await send(await this.tokens.getToken());
164
+ if (res.status === 401) {
165
+ const fresh = await this.tokens.refresh();
166
+ if (fresh)
167
+ res = await send(fresh);
168
+ }
169
+ return { status: res.status, json: parseJson(await res.text()) };
170
+ }
171
+ async call(method, path, body) {
172
+ const { status, json } = await this.request(method, path, body);
173
+ if (status >= 200 && status < 300)
174
+ return obj(json).data ?? json;
175
+ const o = obj(json);
176
+ const code = str(o.code) ?? str(o.error) ?? `http_${status}`;
177
+ let message = str(o.message) ?? `Die API antwortet mit Status ${status}.`;
178
+ const versionStatus = str(o.versionStatus);
179
+ if (versionStatus)
180
+ message += ` (Zustand der Version: ${versionStatus})`;
181
+ const fields = arr(o.fields).filter((f) => typeof f === 'string');
182
+ if (fields.length)
183
+ message += ` (fehlt: ${fields.join(', ')})`;
184
+ let fix = fixFor(status, code);
185
+ if (status === 403 && /\/(publish|rollback)$/.test(path) && !FIXES[code]) {
186
+ fix =
187
+ 'Live schalten und Rollback brauchen das Recht „Website veröffentlichen“. Bitte einen Admin des Workspaces darum.';
188
+ }
189
+ throw new ApiError(status, code, message, fix);
190
+ }
191
+ async listWebsites() {
192
+ return arr(await this.call('GET', '/websites')).map(normalizeWebsite);
193
+ }
194
+ async createWebsite(input) {
195
+ return normalizeWebsite(await this.call('POST', '/websites', input));
196
+ }
197
+ async getWebsite(id) {
198
+ const raw = await this.call('GET', `/websites/${encodeURIComponent(id)}`);
199
+ const o = obj(raw);
200
+ return {
201
+ ...normalizeWebsite(raw),
202
+ domains: arr(o.domains).map(normalizeDomain),
203
+ liveVersion: o.liveVersion ? normalizeVersionSummary(o.liveVersion) : null,
204
+ legalProfileMissing: Array.isArray(o.legalProfileMissing)
205
+ ? o.legalProfileMissing.filter((f) => typeof f === 'string')
206
+ : null,
207
+ };
208
+ }
209
+ async getContent(id) {
210
+ return this.call('GET', `/websites/${encodeURIComponent(id)}/content`);
211
+ }
212
+ async listVersions(id, limit = 10) {
213
+ return arr(await this.call('GET', `/websites/${encodeURIComponent(id)}/versions?limit=${limit}`)).map(normalizeVersionSummary);
214
+ }
215
+ async prepareUpload(id, input) {
216
+ const o = obj(await this.call('POST', `/websites/${encodeURIComponent(id)}/versions`, input));
217
+ const versionId = str(o.versionId);
218
+ const uploadUrl = str(o.uploadUrl);
219
+ if (!versionId || !uploadUrl) {
220
+ throw new CliError('bad_response', 'Die API hat keine Upload-Adresse geliefert.', 'Versuche es erneut.', EXIT.api);
221
+ }
222
+ const headers = Object.fromEntries(Object.entries(obj(o.uploadHeaders)).filter((e) => typeof e[1] === 'string'));
223
+ return {
224
+ versionId,
225
+ uploadUrl,
226
+ uploadMethod: str(o.uploadMethod) ?? 'PUT',
227
+ expiresAt: str(o.expiresAt),
228
+ uploadHeaders: headers,
229
+ };
230
+ }
231
+ async uploadSource(upload, body) {
232
+ let res;
233
+ try {
234
+ // Signierte URL: kein Authorization-Header, genau die vorgegebenen Header. `Content-Length` ist
235
+ // mitsigniert; fetch setzt ihn selbst aus dem Body (gleicher Wert), doppelt setzen geht nicht.
236
+ const headers = Object.fromEntries(Object.entries(upload.uploadHeaders).filter(([k]) => !['content-length', 'host'].includes(k.toLowerCase())));
237
+ const expected = upload.uploadHeaders['Content-Length'] ?? upload.uploadHeaders['content-length'];
238
+ if (expected !== undefined && Number(expected) !== body.byteLength) {
239
+ throw new Error(`Größe passt nicht zur Ankündigung (${body.byteLength} statt ${expected} Bytes)`);
240
+ }
241
+ res = await this.fetchImpl(upload.uploadUrl, { method: upload.uploadMethod, headers, body });
242
+ }
243
+ catch (e) {
244
+ throw new CliError('upload_failed', `Hochladen fehlgeschlagen (${e.message}).`, 'Führe `npx dealsystem deploy` erneut aus.', EXIT.api);
245
+ }
246
+ if (!res.ok) {
247
+ throw new CliError('upload_failed', `Hochladen fehlgeschlagen (Status ${res.status}).`, res.status === 403
248
+ ? 'Die Upload-Adresse ist abgelaufen. Führe `npx dealsystem deploy` erneut aus.'
249
+ : 'Führe `npx dealsystem deploy` erneut aus.', EXIT.api);
250
+ }
251
+ }
252
+ async completeUpload(id, versionId) {
253
+ return normalizeVersion(await this.call('POST', `/websites/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/complete`, {}));
254
+ }
255
+ async getVersion(id, versionId) {
256
+ return normalizeVersion(await this.call('GET', `/websites/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}`));
257
+ }
258
+ /** Antwort `{ site, release }`; `release` ist `null`, wenn die Version schon live war. */
259
+ release(raw, fallbackVersion) {
260
+ const o = obj(raw);
261
+ const site = normalizeWebsite(o.site);
262
+ return {
263
+ liveVersionId: site.liveVersionId ?? fallbackVersion,
264
+ changed: o.release !== null,
265
+ url: site.primaryHost
266
+ ? `https://${site.primaryHost}`
267
+ : site.defaultHost
268
+ ? `https://${site.defaultHost}`
269
+ : null,
270
+ };
271
+ }
272
+ async publish(id, versionId) {
273
+ const raw = await this.call('POST', `/websites/${encodeURIComponent(id)}/publish`, {
274
+ versionId,
275
+ confirm: true,
276
+ });
277
+ return this.release(raw, versionId);
278
+ }
279
+ async rollback(id, versionId) {
280
+ const raw = await this.call('POST', `/websites/${encodeURIComponent(id)}/rollback`, {
281
+ ...(versionId ? { versionId } : {}),
282
+ confirm: true,
283
+ });
284
+ return this.release(raw, versionId ?? '');
285
+ }
286
+ async listSlots(id) {
287
+ const o = obj(await this.call('GET', `/websites/${encodeURIComponent(id)}/slots`));
288
+ return arr(o.slots).map(normalizeSlot);
289
+ }
290
+ async prepareImageUpload(id, input) {
291
+ const o = obj(await this.call('POST', `/websites/${encodeURIComponent(id)}/media`, input));
292
+ const upload = obj(o.upload);
293
+ const uploadId = str(o.uploadId);
294
+ const url = str(upload.url);
295
+ if (!uploadId || !url) {
296
+ throw new CliError('bad_response', 'Die API hat keine Upload-Adresse geliefert.', 'Versuche es erneut.', EXIT.api);
297
+ }
298
+ return {
299
+ uploadId,
300
+ url,
301
+ method: str(upload.method) ?? 'PUT',
302
+ headers: Object.fromEntries(Object.entries(obj(upload.headers)).filter((e) => typeof e[1] === 'string')),
303
+ expiresAt: str(upload.expiresAt),
304
+ };
305
+ }
306
+ async uploadImage(upload, body) {
307
+ let res;
308
+ try {
309
+ // Signierte URL wie beim Quellpaket: kein Authorization-Header, `Content-Length` setzt fetch selbst.
310
+ const headers = Object.fromEntries(Object.entries(upload.headers).filter(([k]) => !['content-length', 'host'].includes(k.toLowerCase())));
311
+ res = await this.fetchImpl(upload.url, { method: upload.method, headers, body });
312
+ }
313
+ catch (e) {
314
+ throw new CliError('upload_failed', `Hochladen des Fotos fehlgeschlagen (${e.message}).`, 'Führe den Befehl erneut aus.', EXIT.api);
315
+ }
316
+ if (!res.ok) {
317
+ throw new CliError('upload_failed', `Hochladen des Fotos fehlgeschlagen (Status ${res.status}).`, 'Führe den Befehl erneut aus; die Upload-Adresse gilt nur 15 Minuten.', EXIT.api);
318
+ }
319
+ }
320
+ async completeImageUpload(id, uploadId, input) {
321
+ const o = obj(await this.call('POST', `/websites/${encodeURIComponent(id)}/media/${encodeURIComponent(uploadId)}/complete`, input));
322
+ return o.slot ? normalizeSlot(o.slot) : null;
323
+ }
324
+ async getSourceDownload(id, versionId) {
325
+ const o = obj(await this.call('GET', `/websites/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/source`));
326
+ const download = obj(o.download);
327
+ const url = str(download.url);
328
+ const sha256 = str(o.sha256);
329
+ const bytes = num(o.bytes);
330
+ if (!url || !sha256 || !/^[0-9a-f]{64}$/.test(sha256) || bytes === null) {
331
+ throw new CliError('bad_response', 'Die API hat keine gültige Download-Adresse geliefert.', 'Versuche es erneut.', EXIT.api);
332
+ }
333
+ return {
334
+ versionId: str(o.versionId) ?? versionId,
335
+ versionNumber: num(o.versionNumber) ?? 0,
336
+ trigger: str(o.trigger) ?? 'upload',
337
+ codeVersionId: str(o.codeVersionId) ?? versionId,
338
+ codeVersionNumber: num(o.codeVersionNumber),
339
+ sha256,
340
+ bytes,
341
+ url,
342
+ expiresAt: str(download.expiresAt),
343
+ };
344
+ }
345
+ async downloadSource(source, maxBytes) {
346
+ // Nur https (http allein für localhost wie bei der API-Adresse): die Antwort wird entpackt.
347
+ let target;
348
+ try {
349
+ target = new URL(source.url);
350
+ }
351
+ catch {
352
+ target = new URL('invalid:');
353
+ }
354
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(target.hostname);
355
+ if (target.protocol !== 'https:' && !(target.protocol === 'http:' && loopback)) {
356
+ throw new CliError('bad_response', 'Die API hat eine unsichere Download-Adresse geliefert.', 'Versuche es erneut. Bleibt der Fehler, melde ihn an DealSystem.', EXIT.api);
357
+ }
358
+ const tooLarge = () => new CliError('download_too_large', `Das Quellpaket ist größer als erwartet (mehr als ${maxBytes} Bytes).`, 'Nichts wurde geschrieben. Versuche es erneut; bleibt der Fehler, melde ihn an DealSystem.', EXIT.api);
359
+ let res;
360
+ try {
361
+ // Signierte Adresse: kein Authorization-Header (der Token gehört nicht zum Speicher).
362
+ res = await this.fetchImpl(target.toString(), { method: 'GET', redirect: 'error' });
363
+ }
364
+ catch (e) {
365
+ throw new CliError('download_failed', `Herunterladen fehlgeschlagen (${e.message}).`, 'Führe `npx dealsystem pull` erneut aus.', EXIT.api);
366
+ }
367
+ if (!res.ok) {
368
+ await res.body?.cancel().catch(() => { });
369
+ throw new CliError('download_failed', `Herunterladen fehlgeschlagen (Status ${res.status}).`, res.status === 403
370
+ ? 'Die Download-Adresse ist abgelaufen. Führe `npx dealsystem pull` erneut aus.'
371
+ : 'Führe `npx dealsystem pull` erneut aus.', EXIT.api);
372
+ }
373
+ const announced = Number(res.headers.get('content-length') ?? NaN);
374
+ if (Number.isFinite(announced) && announced > maxBytes) {
375
+ await res.body?.cancel().catch(() => { });
376
+ throw tooLarge();
377
+ }
378
+ const chunks = [];
379
+ let total = 0;
380
+ const reader = res.body?.getReader();
381
+ if (reader) {
382
+ for (;;) {
383
+ const { done, value } = await reader.read();
384
+ if (done)
385
+ break;
386
+ total += value.byteLength;
387
+ if (total > maxBytes) {
388
+ await reader.cancel().catch(() => { });
389
+ throw tooLarge();
390
+ }
391
+ chunks.push(value);
392
+ }
393
+ }
394
+ const out = new Uint8Array(total);
395
+ let at = 0;
396
+ for (const c of chunks) {
397
+ out.set(c, at);
398
+ at += c.byteLength;
399
+ }
400
+ return out;
401
+ }
402
+ async devLead(id, body) {
403
+ const { status, json } = await this.request('POST', `/websites/${encodeURIComponent(id)}/dev/leads`, body);
404
+ return { status, body: json };
405
+ }
406
+ }
@@ -0,0 +1,9 @@
1
+ import type { WebsiteDetails } from './types.js';
2
+ export interface LegalStatus {
3
+ /** `null`: Der Server liefert keinen Stand. */
4
+ complete: boolean | null;
5
+ /** Fehlende Pflichtangaben als Schlüssel des Servers (`imprintHtml` …). */
6
+ missing: string[] | null;
7
+ }
8
+ export declare function legalStatus(site: Pick<WebsiteDetails, 'legalProfileMissing'>): LegalStatus;
9
+ export declare function legalStatusLine(status: LegalStatus): string;
@@ -0,0 +1,20 @@
1
+ // Stand der Rechtstexte, wie ihn der Server jetzt meldet (`legalProfileMissing`). `publish` und `status` geben
2
+ // ihn aus, damit der Agent nicht aus einer veralteten `.dealsystem/content.json` rät.
3
+ const LABELS = {
4
+ imprintHtml: 'Impressum',
5
+ privacyHtml: 'Datenschutzerklärung',
6
+ company: 'Firmenname',
7
+ email: 'E-Mail-Adresse',
8
+ };
9
+ export function legalStatus(site) {
10
+ const missing = site.legalProfileMissing;
11
+ return { complete: missing === null ? null : missing.length === 0, missing };
12
+ }
13
+ export function legalStatusLine(status) {
14
+ if (status.missing === null)
15
+ return 'Rechtstexte im CRM: Stand unbekannt (der Server meldet ihn nicht).';
16
+ if (status.missing.length === 0)
17
+ return 'Rechtstexte im CRM: vollständig (Impressum, Datenschutzerklärung, Firmenname, E-Mail-Adresse).';
18
+ const names = status.missing.map((key) => LABELS[key] ?? key).join(', ');
19
+ return `Rechtstexte im CRM: es fehlen ${names}. Der Inhaber trägt sie unter „Eigene Website → Rechtliches“ ein.`;
20
+ }
@@ -0,0 +1,35 @@
1
+ import type { FetchLike } from './http.js';
2
+ export declare const CLI_CLIENT_ID = "dealsystem-cli";
3
+ export declare const CLI_SCOPES = "website:read website:write offline_access";
4
+ export interface DeviceAuthorization {
5
+ deviceCode: string;
6
+ userCode: string;
7
+ verificationUri: string;
8
+ verificationUriComplete: string;
9
+ expiresIn: number;
10
+ interval: number;
11
+ }
12
+ export interface TokenSet {
13
+ accessToken: string;
14
+ refreshToken: string | null;
15
+ /** Unix-Millisekunden. */
16
+ expiresAt: number;
17
+ scope: string | null;
18
+ }
19
+ export type PollResult = {
20
+ kind: 'pending';
21
+ } | {
22
+ kind: 'slow_down';
23
+ } | {
24
+ kind: 'denied';
25
+ } | {
26
+ kind: 'expired';
27
+ } | {
28
+ kind: 'tokens';
29
+ tokens: TokenSet;
30
+ };
31
+ /** Audience der CLI-Tokens: `<issuer>/api/v1`. */
32
+ export declare function apiResource(apiUrl: string): string;
33
+ export declare function startDeviceAuthorization(apiUrl: string, fetchImpl: FetchLike): Promise<DeviceAuthorization>;
34
+ export declare function pollDeviceToken(apiUrl: string, deviceCode: string, fetchImpl: FetchLike, now: number): Promise<PollResult>;
35
+ export declare function refreshTokens(apiUrl: string, refreshToken: string, fetchImpl: FetchLike, now: number): Promise<TokenSet | null>;