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
@@ -0,0 +1,178 @@
1
+ // `dealsystem pull` — Quellcode einer Version aus DealSystem holen, z. B. auf einem neuen Rechner.
2
+ //
3
+ // Ablauf: Seite wählen (wie `init`), Zielordner prüfen (neu oder leer, sonst Abbruch VOR jedem Download),
4
+ // Version wählen (Standard: live), signierte Adresse holen, Paket mit Größengrenze laden, SHA-256 prüfen,
5
+ // sicher entpacken (`project/untar.ts`) in einen Temp-Ordner neben dem Ziel, `siteId` eintragen, dann
6
+ // umbenennen. Scheitert etwas, bleibt nichts Halbes liegen.
7
+ //
8
+ // Nicht im Paket, weil `deploy` es nie hochlädt: `node_modules`, `.dealsystem/`, Punkt-Dateien wie
9
+ // `.gitignore` und `.claude/`. `.gitignore` und `CLAUDE.md` schreibt `pull` neu wie der Starter; Skills und
10
+ // Cursor-Regel legt `sync` nach `npm install` aus dem installierten SDK wieder an.
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
13
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
14
+ import { CliError, EXIT } from '../api/errors.js';
15
+ import { defaultSiteConfig, readSiteConfig, SITE_CONFIG_FILE, writeSiteIdIntoConfig, } from '../project/siteConfig.js';
16
+ import { extractTarGz, UNTAR_LIMITS, UnsafeArchiveError } from '../project/untar.js';
17
+ import { UPLOAD_MAX_BYTES } from '../project/uploadFiles.js';
18
+ import { selectExistingSite } from './site.js';
19
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20
+ /** Wie `_gitignore` im Starter. */
21
+ export const PULL_GITIGNORE = 'node_modules/\nbuild/\n.svelte-kit/\n.dealsystem/\n.env\n.env.*\n.DS_Store\n';
22
+ /** Wie im Starter: Claude Code liest damit AGENTS.md. */
23
+ export const PULL_CLAUDE_MD = '@AGENTS.md\n';
24
+ /** Grenzen; Tests setzen kleinere. */
25
+ export const PULL_LIMITS = {
26
+ maxDownloadBytes: UPLOAD_MAX_BYTES,
27
+ untar: UNTAR_LIMITS,
28
+ };
29
+ function isEmptyDir(path) {
30
+ return readdirSync(path).length === 0;
31
+ }
32
+ /** Zielordner: Argument, sonst `--dir`, sonst `./<slug>`. Er muss fehlen oder leer sein. */
33
+ function targetDir(ctx, site) {
34
+ const arg = ctx.positionals[0];
35
+ const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(site.slug) ? site.slug : 'website';
36
+ const target = arg
37
+ ? isAbsolute(arg)
38
+ ? arg
39
+ : resolve(ctx.io.cwd, arg)
40
+ : ctx.str('dir')
41
+ ? ctx.projectDir
42
+ : join(ctx.io.cwd, slug);
43
+ if (existsSync(target)) {
44
+ if (!statSync(target).isDirectory()) {
45
+ throw new CliError('target_not_empty', `${target} gibt es schon, und es ist kein Ordner.`, 'Nenne einen neuen Ordner: `npx dealsystem pull <ordner>`.', EXIT.usage, { directory: target });
46
+ }
47
+ if (!isEmptyDir(target)) {
48
+ throw new CliError('target_not_empty', `Der Ordner ${target} ist nicht leer. \`pull\` schreibt nie über vorhandene Dateien.`, 'Nenne einen neuen oder leeren Ordner: `npx dealsystem pull <ordner>`.', EXIT.usage, { directory: target });
49
+ }
50
+ }
51
+ return target;
52
+ }
53
+ async function versionId(ctx, site) {
54
+ const wanted = ctx.str('version');
55
+ const api = ctx.api();
56
+ if (wanted) {
57
+ const versions = await api.listVersions(site.id, 50);
58
+ const hit = versions.find((v) => v.id === wanted || String(v.number) === wanted);
59
+ if (hit)
60
+ return hit.id;
61
+ if (UUID.test(wanted))
62
+ return wanted.toLowerCase();
63
+ throw new CliError('version_not_found', `Die Version \`${wanted}\` gibt es nicht (unter den letzten 50).`, 'Zeige die Versionen mit `npx dealsystem status --site <id>` oder nimm ihre ID.', EXIT.usage);
64
+ }
65
+ const details = await api.getWebsite(site.id);
66
+ const live = details.liveVersion?.id || details.liveVersionId || site.liveVersionId;
67
+ if (!live) {
68
+ throw new CliError('no_live_version', `Die Seite ${site.name} hat noch keine Live-Version.`, 'Hole eine bestimmte Version mit `npx dealsystem pull --version <nummer>`; die Nummern zeigt `npx dealsystem status --site <id>`.', EXIT.usage);
69
+ }
70
+ return live;
71
+ }
72
+ /** `siteId` in dealsystem.config.ts auf diese Seite setzen. `false`, wenn das nicht ging. */
73
+ function linkSite(dir, siteId) {
74
+ const path = join(dir, SITE_CONFIG_FILE);
75
+ if (!existsSync(path)) {
76
+ writeFileSync(path, defaultSiteConfig(siteId));
77
+ return true;
78
+ }
79
+ const code = readFileSync(path, 'utf8');
80
+ if (readSiteConfig(code).data?.siteId === siteId)
81
+ return true;
82
+ const next = writeSiteIdIntoConfig(code, siteId);
83
+ if (next === null)
84
+ return false;
85
+ writeFileSync(path, next);
86
+ return true;
87
+ }
88
+ function writeIfMissing(path, content) {
89
+ if (!existsSync(path))
90
+ writeFileSync(path, content);
91
+ }
92
+ export async function pullCommand(ctx) {
93
+ if (ctx.positionals.length > 1) {
94
+ throw new CliError('invalid_arguments', '`pull` nimmt höchstens einen Ordner.', 'Aufruf: `npx dealsystem pull [ordner] [--site <id|slug>] [--version <nummer|id>]`.', EXIT.usage);
95
+ }
96
+ const site = await selectExistingSite(ctx, 'pull');
97
+ // Vor jedem Download: ein nicht leerer Ordner bricht ab, ohne dass etwas geschrieben wird.
98
+ const target = targetDir(ctx, site);
99
+ const api = ctx.api();
100
+ const source = await api.getSourceDownload(site.id, await versionId(ctx, site));
101
+ const limits = PULL_LIMITS;
102
+ if (source.bytes > limits.maxDownloadBytes) {
103
+ throw new CliError('download_too_large', `Das Quellpaket hat ${source.bytes} Bytes, erlaubt sind ${limits.maxDownloadBytes}.`, 'Nichts wurde geschrieben. Melde das an DealSystem.', EXIT.api);
104
+ }
105
+ ctx.progress(`Lade den Quellcode von Version ${source.codeVersionNumber ?? source.versionNumber} …`);
106
+ // Höchstens die angekündigte Größe: mehr Bytes heißt, es kommt etwas anderes als angekündigt.
107
+ const data = await api.downloadSource(source, Math.min(source.bytes, limits.maxDownloadBytes));
108
+ const sha = createHash('sha256').update(data).digest('hex');
109
+ if (sha !== source.sha256) {
110
+ throw new CliError('checksum_mismatch', 'Das heruntergeladene Quellpaket passt nicht zur Prüfsumme.', 'Nichts wurde geschrieben. Führe `npx dealsystem pull` erneut aus.', EXIT.api);
111
+ }
112
+ const parent = dirname(target);
113
+ mkdirSync(parent, { recursive: true });
114
+ const staging = mkdtempSync(join(parent, `.${basename(target)}.dealsystem-pull-`));
115
+ const stage = join(staging, 'site');
116
+ let result;
117
+ let siteIdSet;
118
+ try {
119
+ try {
120
+ result = extractTarGz(data, stage, limits.untar);
121
+ }
122
+ catch (e) {
123
+ if (e instanceof UnsafeArchiveError) {
124
+ throw new CliError('unsafe_archive', `Das Quellpaket wurde nicht entpackt: ${e.message}`, 'Nichts wurde geschrieben. Nimm eine andere Version (`--version <nummer>`) oder melde das an DealSystem.', EXIT.failed);
125
+ }
126
+ throw e;
127
+ }
128
+ siteIdSet = linkSite(stage, site.id);
129
+ writeIfMissing(join(stage, '.gitignore'), PULL_GITIGNORE);
130
+ writeIfMissing(join(stage, 'CLAUDE.md'), PULL_CLAUDE_MD);
131
+ // Erneut prüfen: In der Zwischenzeit kann jemand den Ordner befüllt haben.
132
+ if (existsSync(target)) {
133
+ if (!statSync(target).isDirectory() || !isEmptyDir(target)) {
134
+ throw new CliError('target_not_empty', `Der Ordner ${target} ist inzwischen nicht mehr leer.`, 'Nenne einen neuen Ordner: `npx dealsystem pull <ordner>`.', EXIT.usage);
135
+ }
136
+ rmdirSync(target);
137
+ }
138
+ renameSync(stage, target);
139
+ }
140
+ finally {
141
+ rmSync(staging, { recursive: true, force: true });
142
+ }
143
+ const shown = relative(ctx.io.cwd, target) || '.';
144
+ const cdPath = shown.startsWith('..') || isAbsolute(shown) ? target : shown;
145
+ const fromCode = source.trigger === 'content' && source.codeVersionId !== source.versionId
146
+ ? ` Version ${source.versionNumber} ist ein Inhalts-Stand; geholt wurde ihr Code aus Version ${source.codeVersionNumber ?? source.codeVersionId}.`
147
+ : '';
148
+ const lines = [
149
+ `Quellcode von ${site.name}, Version ${source.versionNumber}, liegt in ${target} (${result.files} Dateien).${fromCode}`,
150
+ siteIdSet
151
+ ? `\`siteId\` steht in ${SITE_CONFIG_FILE}; \`deploy\` lädt in diese Seite hoch.`
152
+ : `Achtung: \`siteId\` ließ sich nicht in ${SITE_CONFIG_FILE} eintragen. Führe im Ordner \`npx dealsystem init --site ${site.id}\` aus.`,
153
+ 'Nächste Schritte:',
154
+ ` cd ${cdPath}`,
155
+ ' npm install',
156
+ ' npx dealsystem sync (holt die Inhalte und legt die Skills für deinen KI-Agenten wieder an)',
157
+ 'Danach wie gewohnt ändern, prüfen und mit `npx dealsystem deploy` hochladen.',
158
+ ];
159
+ return {
160
+ exitCode: EXIT.ok,
161
+ data: {
162
+ siteId: site.id,
163
+ slug: site.slug,
164
+ directory: target,
165
+ versionId: source.versionId,
166
+ versionNumber: source.versionNumber,
167
+ trigger: source.trigger,
168
+ codeVersionId: source.codeVersionId,
169
+ codeVersionNumber: source.codeVersionNumber,
170
+ files: result.files,
171
+ bytes: result.bytes,
172
+ sha256: source.sha256,
173
+ siteIdSet,
174
+ next: [`cd ${cdPath}`, 'npm install', 'npx dealsystem sync'],
175
+ },
176
+ text: lines.join('\n'),
177
+ };
178
+ }
@@ -0,0 +1,9 @@
1
+ import type { Website } from '../api/types.js';
2
+ import type { CommandContext, CommandResult } from '../cli/context.js';
3
+ /**
4
+ * Vorhandene Seite: `--site <id|slug>`, sonst die einzige des Workspaces; bei mehreren ein Fehler mit
5
+ * Liste (für `init` und `pull`).
6
+ */
7
+ export declare function selectExistingSite(ctx: CommandContext, command: 'init' | 'pull'): Promise<Website>;
8
+ export declare function initCommand(ctx: CommandContext): Promise<CommandResult>;
9
+ export declare function statusCommand(ctx: CommandContext): Promise<CommandResult>;
@@ -0,0 +1,84 @@
1
+ // `dealsystem init` (Seite wählen oder anlegen, `siteId` eintragen) und `dealsystem status`.
2
+ import { writeFileSync } from 'node:fs';
3
+ import { CliError, EXIT } from '../api/errors.js';
4
+ import { legalStatus, legalStatusLine } from '../api/legal.js';
5
+ import { defaultSiteConfig, SITE_CONFIG_FILE, writeSiteIdIntoConfig } from '../project/siteConfig.js';
6
+ function siteLine(s) {
7
+ return `${s.id} ${s.slug} ${s.name}`;
8
+ }
9
+ async function chooseSite(ctx) {
10
+ const api = ctx.api();
11
+ if (ctx.flag('create')) {
12
+ const name = ctx.str('name');
13
+ const slug = ctx.str('slug');
14
+ if (!name || !slug) {
15
+ throw new CliError('missing_arguments', '`--create` braucht `--name` und `--slug`.', 'Beispiel: `npx dealsystem init --create --name "Muster Immobilien" --slug muster-immobilien`.', EXIT.usage);
16
+ }
17
+ return { site: await api.createWebsite({ name, slug }), created: true };
18
+ }
19
+ return { site: await selectExistingSite(ctx, 'init'), created: false };
20
+ }
21
+ /**
22
+ * Vorhandene Seite: `--site <id|slug>`, sonst die einzige des Workspaces; bei mehreren ein Fehler mit
23
+ * Liste (für `init` und `pull`).
24
+ */
25
+ export async function selectExistingSite(ctx, command) {
26
+ const sites = await ctx.api().listWebsites();
27
+ const wanted = ctx.str('site');
28
+ if (wanted) {
29
+ const site = sites.find((s) => s.id === wanted || s.slug === wanted);
30
+ if (!site) {
31
+ throw new CliError('site_not_found', `Die Seite \`${wanted}\` gibt es in diesem Workspace nicht.`, command === 'init'
32
+ ? 'Wähle eine der Seiten aus `data.sites` oder lege eine an mit `--create --name … --slug …`.'
33
+ : 'Wähle eine der Seiten aus `data.sites`.', EXIT.usage, { sites });
34
+ }
35
+ return site;
36
+ }
37
+ if (sites.length === 1)
38
+ return sites[0];
39
+ if (sites.length === 0) {
40
+ throw new CliError('no_sites', 'In diesem Workspace gibt es noch keine Seite.', 'Lege eine an: `npx dealsystem init --create --name "<Name>" --slug <adresse>`.', EXIT.usage, { sites });
41
+ }
42
+ throw new CliError('site_ambiguous', `Es gibt mehrere Seiten:\n${sites.map(siteLine).join('\n')}`, `Wähle eine mit \`npx dealsystem ${command} --site <id oder slug>\`.`, EXIT.usage, { sites });
43
+ }
44
+ export async function initCommand(ctx) {
45
+ const { site, created } = await chooseSite(ctx);
46
+ const current = ctx.readProjectFile(SITE_CONFIG_FILE);
47
+ let next;
48
+ if (current === null)
49
+ next = defaultSiteConfig(site.id);
50
+ else
51
+ next = writeSiteIdIntoConfig(current, site.id);
52
+ if (next === null) {
53
+ throw new CliError('config_unreadable', `In ${SITE_CONFIG_FILE} lässt sich \`siteId\` nicht eintragen.`, `Schreibe \`siteId: '${site.id}'\` in \`defineSite({ … })\`.`, EXIT.failed, { siteId: site.id });
54
+ }
55
+ if (next !== current)
56
+ writeFileSync(ctx.path(SITE_CONFIG_FILE), next);
57
+ return {
58
+ exitCode: EXIT.ok,
59
+ data: { siteId: site.id, name: site.name, slug: site.slug, created, configFile: SITE_CONFIG_FILE },
60
+ text: `${created ? 'Seite angelegt' : 'Seite gewählt'}: ${site.name} (${site.slug}). \`siteId\` steht in ${SITE_CONFIG_FILE}. Nächster Schritt: \`npx dealsystem sync\`.`,
61
+ };
62
+ }
63
+ export async function statusCommand(ctx) {
64
+ const id = ctx.siteId();
65
+ const api = ctx.api();
66
+ const [site, versions] = await Promise.all([api.getWebsite(id), api.listVersions(id, 5)]);
67
+ const live = site.liveVersion;
68
+ const legal = legalStatus(site);
69
+ const lines = [
70
+ `Seite: ${site.name} (${site.slug}), Zustand ${site.status}`,
71
+ `Adresse: ${site.primaryHost ?? site.defaultHost ?? '–'}`,
72
+ `Live: ${live ? `Version ${live.number}` : 'noch nichts live'}`,
73
+ legalStatusLine(legal),
74
+ 'Letzte Versionen:',
75
+ ...(versions.length
76
+ ? versions.map((v) => ` ${v.number} ${v.status} ${v.previewUrl ?? ''} ${v.message ?? ''}`.trimEnd())
77
+ : [' keine']),
78
+ 'Domains:',
79
+ ...(site.domains.length
80
+ ? site.domains.map((d) => ` ${d.host} (${d.kind}${d.active ? ', aktiv' : ', noch nicht aktiv'})`)
81
+ : [' keine']),
82
+ ];
83
+ return { exitCode: EXIT.ok, data: { site, versions, legal }, text: lines.join('\n') };
84
+ }
@@ -0,0 +1,2 @@
1
+ import type { CommandContext, CommandResult } from '../cli/context.js';
2
+ export declare function syncCommand(ctx: CommandContext): Promise<CommandResult>;
@@ -0,0 +1,126 @@
1
+ // `dealsystem sync` — Schnappschuss holen (`.dealsystem/content.json` für dev und Build), Stand im CRM mit
2
+ // dealsystem.config.ts abgleichen, `src/dealsystem.d.ts` anlegen, falls sie fehlt, AGENTS.md-Block erneuern,
3
+ // fehlende Agenten-Dateien (Skills, Cursor-Regel) aus dem installierten SDK anlegen (`project/agentFiles.ts`).
4
+ // Typen erzeugt sync nicht: das SDK leitet sie aus `typeof site` ab.
5
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { dirname } from 'node:path';
7
+ import { CliError, EXIT } from '../api/errors.js';
8
+ import { runCheck } from '../check/run.js';
9
+ import { AGENTS_BLOCK_SOURCE, SDK_PACKAGE } from '../check/sdk.js';
10
+ import { agentFilesNote, restoreAgentFiles } from '../project/agentFiles.js';
11
+ import { updateAgentsMd } from '../project/agentsBlock.js';
12
+ import { readSiteConfig, SITE_CONFIG_FILE } from '../project/siteConfig.js';
13
+ import { canonicalJson, codeSlotKeys, compareSnapshot, CONTENT_FILE, GLOBAL_TYPES_CONTENT, GLOBAL_TYPES_FILE, } from '../project/snapshot.js';
14
+ import { SVELTE_CONFIG_TEMPLATE, VITE_CONFIG_TEMPLATE } from '../project/svelteConfig.js';
15
+ import { createUploadFileSet } from '../project/uploadFiles.js';
16
+ /** Schreibt nur, wenn sich der Inhalt ändert. `true` = geändert. */
17
+ function writeIfChanged(path, content) {
18
+ if (existsSync(path) && readFileSync(path, 'utf8') === content)
19
+ return false;
20
+ mkdirSync(dirname(path), { recursive: true });
21
+ writeFileSync(path, content);
22
+ return true;
23
+ }
24
+ function ensureGitignore(ctx) {
25
+ const path = ctx.path('.gitignore');
26
+ const current = ctx.readProjectFile('.gitignore');
27
+ if (current !== null && /^\/?\.dealsystem\/?$/m.test(current))
28
+ return;
29
+ // Die lokale Kopie der Inhalte gehört nicht ins Git (und geht nie in den Upload).
30
+ writeFileSync(path, current === null ? '.dealsystem/\n' : `${current.replace(/\s*$/, '')}\n.dealsystem/\n`);
31
+ }
32
+ /** Stellt svelte.config.js und vite.config.ts aus dem Starter wieder her, wenn ihre Regeln scheitern. */
33
+ async function fixConfig(ctx) {
34
+ const targets = [
35
+ { file: 'svelte.config.js', rules: ['STR-001', 'SEC-005', 'STR-008'], content: SVELTE_CONFIG_TEMPLATE },
36
+ { file: 'vite.config.ts', rules: ['STR-009'], content: VITE_CONFIG_TEMPLATE },
37
+ ];
38
+ const result = await runCheck({ source: createUploadFileSet(ctx.projectDir) });
39
+ const failing = new Set(result.errors.map((f) => f.rule));
40
+ const fixed = [];
41
+ for (const t of targets) {
42
+ if (!t.rules.some((r) => failing.has(r)))
43
+ continue;
44
+ const target = ctx.path(t.file);
45
+ if (existsSync(target))
46
+ copyFileSync(target, `${target}.bak`);
47
+ writeFileSync(target, t.content);
48
+ fixed.push(t.file);
49
+ }
50
+ return fixed;
51
+ }
52
+ function updateAgents(ctx) {
53
+ const block = ctx.readProjectFile(AGENTS_BLOCK_SOURCE);
54
+ const pkgText = ctx.readProjectFile(`node_modules/${SDK_PACKAGE}/package.json`);
55
+ if (block === null || pkgText === null)
56
+ return 'skipped';
57
+ let version;
58
+ try {
59
+ version = String(JSON.parse(pkgText).version ?? '');
60
+ }
61
+ catch {
62
+ return 'skipped';
63
+ }
64
+ if (!version)
65
+ return 'skipped';
66
+ const next = updateAgentsMd(ctx.readProjectFile('AGENTS.md'), version, block);
67
+ return writeIfChanged(ctx.path('AGENTS.md'), next) ? 'updated' : 'unchanged';
68
+ }
69
+ export async function syncCommand(ctx) {
70
+ const config = readSiteConfig(ctx.readProjectFile(SITE_CONFIG_FILE));
71
+ if (!config.data) {
72
+ const p = config.problems[0];
73
+ throw new CliError('invalid_config', p?.message ?? `${SITE_CONFIG_FILE} ist ungültig.`, p?.fix ?? 'Führe `npx dealsystem init` aus.', EXIT.failed);
74
+ }
75
+ let snapshot = null;
76
+ const contentPath = ctx.path(CONTENT_FILE);
77
+ const offline = ctx.flag('offline');
78
+ if (offline) {
79
+ if (existsSync(contentPath))
80
+ snapshot = JSON.parse(readFileSync(contentPath, 'utf8'));
81
+ }
82
+ else {
83
+ const siteId = ctx.siteId();
84
+ ctx.progress('Hole Inhalte aus dem CRM …');
85
+ snapshot = await ctx.api().getContent(siteId);
86
+ writeIfChanged(contentPath, canonicalJson(snapshot));
87
+ ensureGitignore(ctx);
88
+ }
89
+ const fixedConfig = ctx.flag('fix-config') ? await fixConfig(ctx) : [];
90
+ const typesCreated = !existsSync(ctx.path(GLOBAL_TYPES_FILE));
91
+ if (typesCreated)
92
+ writeIfChanged(ctx.path(GLOBAL_TYPES_FILE), GLOBAL_TYPES_CONTENT);
93
+ const drift = snapshot === null
94
+ ? []
95
+ : compareSnapshot(snapshot, config.data, codeSlotKeys(createUploadFileSet(ctx.projectDir)));
96
+ const agentsMd = updateAgents(ctx);
97
+ const agentFiles = restoreAgentFiles(ctx.projectDir);
98
+ const agentFilesLine = agentFilesNote(agentFiles);
99
+ const notes = [
100
+ offline
101
+ ? snapshot === null
102
+ ? `Offline: ${CONTENT_FILE} fehlt, kein Abgleich mit dem CRM.`
103
+ : `Offline: Abgleich mit der vorhandenen ${CONTENT_FILE}.`
104
+ : `Inhalte gespeichert in ${CONTENT_FILE}.`,
105
+ ...drift.map((d) => `${SITE_CONFIG_FILE} – ${d.message} – ${d.fix}`),
106
+ ...(typesCreated ? [`${GLOBAL_TYPES_FILE} angelegt.`] : []),
107
+ agentsMd === 'skipped'
108
+ ? 'AGENTS.md: kein Block im installierten SDK gefunden, übersprungen.'
109
+ : `AGENTS.md: ${agentsMd === 'updated' ? 'aktualisiert' : 'unverändert'}.`,
110
+ ...(agentFilesLine ? [agentFilesLine] : []),
111
+ ...fixedConfig.map((f) => `${f} wiederhergestellt (alte Fassung: ${f}.bak).`),
112
+ drift.length ? `${drift.length} Abweichung(en) zwischen CRM und Code.` : 'CRM und Code passen zusammen.',
113
+ ];
114
+ return {
115
+ exitCode: EXIT.ok,
116
+ data: {
117
+ contentFile: offline ? null : CONTENT_FILE,
118
+ drift,
119
+ typesFileCreated: typesCreated,
120
+ agentsMd,
121
+ agentFiles,
122
+ fixedConfig,
123
+ },
124
+ text: notes.join('\n'),
125
+ };
126
+ }
@@ -0,0 +1,10 @@
1
+ export * from './check/index.js';
2
+ export { run, helpText, COMMANDS } from './cli/main.js';
3
+ export { nodeIO, type CliIO } from './cli/io.js';
4
+ export { EXIT, CliError, ApiError } from './api/errors.js';
5
+ export type { DeployApi } from './api/types.js';
6
+ export { HttpDeployApi } from './api/http.js';
7
+ export { selectUploadFiles, isUploadPath, UPLOAD_MAX_BYTES } from './project/uploadFiles.js';
8
+ export { createTarGz, readTarGz } from './project/tar.js';
9
+ export { readSiteConfig } from './project/siteConfig.js';
10
+ export { canonicalJson, compareSnapshot, type DriftItem } from './project/snapshot.js';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // Paket `dealsystem`: CLI und Regelkatalog. Für den Build-Host ist `dealsystem/check` der Einstieg.
2
+ export * from './check/index.js';
3
+ export { run, helpText, COMMANDS } from './cli/main.js';
4
+ export { nodeIO } from './cli/io.js';
5
+ export { EXIT, CliError, ApiError } from './api/errors.js';
6
+ export { HttpDeployApi } from './api/http.js';
7
+ export { selectUploadFiles, isUploadPath, UPLOAD_MAX_BYTES } from './project/uploadFiles.js';
8
+ export { createTarGz, readTarGz } from './project/tar.js';
9
+ export { readSiteConfig } from './project/siteConfig.js';
10
+ export { canonicalJson, compareSnapshot } from './project/snapshot.js';
@@ -0,0 +1,17 @@
1
+ export interface AgentFilesResult {
2
+ /** `null`, wenn das installierte SDK keine Agenten-Dateien mitbringt (älter oder nicht installiert). */
3
+ skipped: 'no_sdk' | 'invalid_manifest' | null;
4
+ /** Neu angelegt. */
5
+ restored: string[];
6
+ /** Unveränderte frühere Fassung durch die neue ersetzt. */
7
+ updated: string[];
8
+ /** Vom Kunden geändert oder kein normaler Ordner/keine normale Datei: unberührt. */
9
+ kept: string[];
10
+ /** Eintrag im Manifest abgelehnt (Pfad unzulässig, Inhalt passt nicht zur Prüfsumme). */
11
+ rejected: string[];
12
+ }
13
+ /** `.claude/…` oder `.cursor/…`, nur harmlose Segmente (kein `.`, `..`, keine Trenner, keine Laufwerke). */
14
+ export declare function isAllowedAgentTarget(target: string): boolean;
15
+ export declare function restoreAgentFiles(projectDir: string): AgentFilesResult;
16
+ /** Zeile für die Ausgabe von `sync`; `null`, wenn nichts zu sagen ist. */
17
+ export declare function agentFilesNote(r: AgentFilesResult): string | null;
@@ -0,0 +1,156 @@
1
+ // Agenten-Dateien (Skills unter `.claude/`, Cursor-Regel unter `.cursor/`) aus dem installierten SDK ins
2
+ // Projekt legen. `deploy` lädt Punkt-Ordner nie hoch, nach `pull` fehlen sie also; `sync` stellt sie wieder her.
3
+ //
4
+ // Quelle: `node_modules/@dealsystem/site/agent-files/` mit `manifest.json` (erzeugt von
5
+ // scripts/build-agent-docs.mjs aus dem Starter). Regeln:
6
+ // - Fehlt eine Datei, wird sie angelegt.
7
+ // - Gleicht eine vorhandene Datei byte-genau einer früher ausgelieferten Fassung (`previous`), wird sie erneuert.
8
+ // - Alles andere hat der Kunde geändert und bleibt unberührt.
9
+ // - Ziele nur unter `.claude/` und `.cursor/`, kein `..`, keine Links im Pfad: das Manifest liegt in
10
+ // `node_modules` und gilt nicht als vertrauenswürdig.
11
+ import { createHash } from 'node:crypto';
12
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
13
+ import { dirname, join, sep } from 'node:path';
14
+ import { AGENT_FILES_SOURCE } from '../check/sdk.js';
15
+ const SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
16
+ const SHA = /^[0-9a-f]{64}$/;
17
+ const sha256 = (data) => createHash('sha256').update(data).digest('hex');
18
+ /** `.claude/…` oder `.cursor/…`, nur harmlose Segmente (kein `.`, `..`, keine Trenner, keine Laufwerke). */
19
+ export function isAllowedAgentTarget(target) {
20
+ const parts = target.split('/');
21
+ if (parts.length < 2 || (parts[0] !== '.claude' && parts[0] !== '.cursor'))
22
+ return false;
23
+ return parts.slice(1).every((p) => SEGMENT.test(p));
24
+ }
25
+ function parseManifest(text) {
26
+ let raw;
27
+ try {
28
+ raw = JSON.parse(text);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ const files = raw?.files;
34
+ if (!Array.isArray(files))
35
+ return null;
36
+ const out = [];
37
+ for (const f of files) {
38
+ const o = f;
39
+ if (typeof o?.target !== 'string' || typeof o.source !== 'string' || typeof o.sha256 !== 'string')
40
+ return null;
41
+ const previous = Array.isArray(o.previous)
42
+ ? o.previous.filter((h) => typeof h === 'string')
43
+ : [];
44
+ out.push({ target: o.target, source: o.source, sha256: o.sha256, previous });
45
+ }
46
+ return out;
47
+ }
48
+ const inside = (root, path) => path === root || path.startsWith(root + sep);
49
+ /** Kein Link zwischen Projektordner und Ziel: sonst landete die Datei außerhalb des Projekts. */
50
+ function linkFreeParents(projectDir, target) {
51
+ let current = projectDir;
52
+ for (const part of target.split('/').slice(0, -1)) {
53
+ current = join(current, part);
54
+ if (!existsSync(current) && !isDanglingLink(current))
55
+ return true;
56
+ const st = lstatSync(current);
57
+ if (st.isSymbolicLink() || !st.isDirectory())
58
+ return false;
59
+ }
60
+ return true;
61
+ }
62
+ function isDanglingLink(path) {
63
+ try {
64
+ return lstatSync(path).isSymbolicLink();
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ export function restoreAgentFiles(projectDir) {
71
+ const result = { skipped: null, restored: [], updated: [], kept: [], rejected: [] };
72
+ const sdkDir = join(projectDir, AGENT_FILES_SOURCE);
73
+ let manifestText;
74
+ let sdkRoot;
75
+ try {
76
+ sdkRoot = realpathSync(sdkDir);
77
+ manifestText = readFileSync(join(sdkRoot, 'manifest.json'), 'utf8');
78
+ }
79
+ catch {
80
+ return { ...result, skipped: 'no_sdk' };
81
+ }
82
+ const entries = parseManifest(manifestText);
83
+ if (!entries)
84
+ return { ...result, skipped: 'invalid_manifest' };
85
+ for (const e of entries) {
86
+ // Quelle = Ziel ohne den Punkt am Anfang; so kann das Manifest keine fremde Datei unterschieben.
87
+ if (!isAllowedAgentTarget(e.target) || e.source !== e.target.slice(1) || !SHA.test(e.sha256)) {
88
+ result.rejected.push(e.target);
89
+ continue;
90
+ }
91
+ let content;
92
+ try {
93
+ const sourcePath = realpathSync(join(sdkRoot, ...e.source.split('/')));
94
+ if (!inside(sdkRoot, sourcePath))
95
+ throw new Error('außerhalb');
96
+ content = readFileSync(sourcePath);
97
+ }
98
+ catch {
99
+ result.rejected.push(e.target);
100
+ continue;
101
+ }
102
+ if (sha256(content) !== e.sha256) {
103
+ result.rejected.push(e.target);
104
+ continue;
105
+ }
106
+ if (!linkFreeParents(projectDir, e.target)) {
107
+ result.kept.push(e.target);
108
+ continue;
109
+ }
110
+ const targetPath = join(projectDir, ...e.target.split('/'));
111
+ let existing;
112
+ try {
113
+ existing = lstatSync(targetPath);
114
+ }
115
+ catch {
116
+ existing = null;
117
+ }
118
+ if (!existing) {
119
+ mkdirSync(dirname(targetPath), { recursive: true });
120
+ // `wx`: entsteht die Datei zwischendurch, wird nichts überschrieben.
121
+ writeFileSync(targetPath, content, { flag: 'wx' });
122
+ result.restored.push(e.target);
123
+ continue;
124
+ }
125
+ if (!existing.isFile()) {
126
+ result.kept.push(e.target);
127
+ continue;
128
+ }
129
+ const current = sha256(readFileSync(targetPath));
130
+ if (current === e.sha256)
131
+ continue;
132
+ if (e.previous.includes(current)) {
133
+ writeFileSync(targetPath, content);
134
+ result.updated.push(e.target);
135
+ }
136
+ else {
137
+ result.kept.push(e.target);
138
+ }
139
+ }
140
+ return result;
141
+ }
142
+ /** Zeile für die Ausgabe von `sync`; `null`, wenn nichts zu sagen ist. */
143
+ export function agentFilesNote(r) {
144
+ if (r.skipped === 'no_sdk')
145
+ return 'Agenten-Dateien: das installierte SDK bringt keine mit, übersprungen.';
146
+ if (r.skipped === 'invalid_manifest')
147
+ return 'Agenten-Dateien: Verzeichnis im SDK unlesbar, übersprungen.';
148
+ const n = (count, one, many) => `${count} ${count === 1 ? one : many}`;
149
+ const parts = [
150
+ r.restored.length && `${n(r.restored.length, 'Agenten-Datei', 'Agenten-Dateien')} wiederhergestellt`,
151
+ r.updated.length && `${n(r.updated.length, 'Agenten-Datei', 'Agenten-Dateien')} aktualisiert`,
152
+ r.kept.length && `${n(r.kept.length, 'geänderte Agenten-Datei', 'geänderte Agenten-Dateien')} behalten`,
153
+ r.rejected.length && `${n(r.rejected.length, 'Eintrag', 'Einträge')} im SDK abgelehnt`,
154
+ ].filter(Boolean);
155
+ return parts.length ? `${parts.join(', ')}.` : null;
156
+ }
@@ -0,0 +1,2 @@
1
+ export declare function renderAgentsBlock(version: string, body: string): string;
2
+ export declare function updateAgentsMd(current: string | null, version: string, body: string): string;
@@ -0,0 +1,14 @@
1
+ // Ersetzt in AGENTS.md nur den markierten DealSystem-Block; was der Kunde darum herum schreibt, bleibt.
2
+ import { AGENTS_BLOCK_END } from '../check/sdk.js';
3
+ const BLOCK_RE = /<!--\s*dealsystem:begin\s+[^\s]+\s*-->[\s\S]*?<!--\s*dealsystem:end\s*-->/;
4
+ export function renderAgentsBlock(version, body) {
5
+ return `<!-- dealsystem:begin ${version} -->\n${body.trim()}\n${AGENTS_BLOCK_END}`;
6
+ }
7
+ export function updateAgentsMd(current, version, body) {
8
+ const block = renderAgentsBlock(version, body);
9
+ if (current === null || current.trim() === '')
10
+ return `${block}\n`;
11
+ if (BLOCK_RE.test(current))
12
+ return current.replace(BLOCK_RE, () => block);
13
+ return `${current.replace(/\s*$/, '')}\n\n${block}\n`;
14
+ }
@@ -0,0 +1,5 @@
1
+ export { findPathLine, readSiteConfig, SITE_CONFIG_FILE, type ConfigProblem, type ConfigProblemKind, type SiteConfigData, type SiteConfigResult, } from '@dealsystem/site/config/static';
2
+ /** Setzt `siteId` in der Konfiguration (für `init`). Gibt den neuen Text zurück. */
3
+ export declare function writeSiteIdIntoConfig(code: string, siteId: string): string | null;
4
+ /** Konfiguration für eine neue Seite, falls noch keine existiert. */
5
+ export declare function defaultSiteConfig(siteId: string): string;
@@ -0,0 +1,35 @@
1
+ // `dealsystem.config.ts`: Der statische Leser liegt im SDK (`@dealsystem/site/config/static`), damit
2
+ // `dealsystemCsp()` und `check` dieselbe Konfiguration sehen. Hier nur, was allein die CLI braucht.
3
+ export { findPathLine, readSiteConfig, SITE_CONFIG_FILE, } from '@dealsystem/site/config/static';
4
+ /** Setzt `siteId` in der Konfiguration (für `init`). Gibt den neuen Text zurück. */
5
+ export function writeSiteIdIntoConfig(code, siteId) {
6
+ const re = /(\bsiteId\s*:\s*)(['"`])[^'"`]*\2/;
7
+ if (re.test(code))
8
+ return code.replace(re, `$1'${siteId}'`);
9
+ const call = /(defineSite\(\s*\{)/;
10
+ if (call.test(code))
11
+ return code.replace(call, `$1\n\tsiteId: '${siteId}',`);
12
+ return null;
13
+ }
14
+ /** Konfiguration für eine neue Seite, falls noch keine existiert. */
15
+ export function defaultSiteConfig(siteId) {
16
+ return [
17
+ "import { defineSite } from '@dealsystem/site/config';",
18
+ '',
19
+ 'export default defineSite({',
20
+ `\tsiteId: '${siteId}',`,
21
+ '\tfunnels: {',
22
+ '\t\tkontakt: {',
23
+ "\t\t\tlabel: 'Kontakt',",
24
+ '\t\t\tfields: [',
25
+ "\t\t\t\t{ name: 'firstName', type: 'text', label: 'Vorname', standardField: 'firstName' },",
26
+ "\t\t\t\t{ name: 'lastName', type: 'text', label: 'Nachname', standardField: 'lastName' },",
27
+ "\t\t\t\t{ name: 'email', type: 'email', label: 'E-Mail', standardField: 'email', required: true },",
28
+ "\t\t\t\t{ name: 'nachricht', type: 'textarea', label: 'Nachricht' },",
29
+ '\t\t\t],',
30
+ '\t\t},',
31
+ '\t},',
32
+ '});',
33
+ '',
34
+ ].join('\n');
35
+ }