@divithselvam/jokebook 0.0.0-stage → 1.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,254 @@
1
+ import { isCI } from 'ci-info';
2
+ import { execa } from 'execa';
3
+ import { createHash } from 'node:crypto';
4
+ import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
5
+ import { createRequire } from 'node:module';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { stripVTControlCharacters } from 'node:util';
9
+ const manifest = createRequire(import.meta.url)('../package.json');
10
+ const config = manifest.jokebook;
11
+ if (!config?.catalog || !config.starter || !config.pnpm || !config.skillsCli || !manifest.engines?.node ||
12
+ !manifest.engines.npm || !manifest.version) {
13
+ throw new Error('package.json is missing the release metadata Jokebook needs.');
14
+ }
15
+ export const release = Object.freeze({
16
+ catalog: config.catalog,
17
+ node: manifest.engines.node,
18
+ npm: manifest.engines.npm,
19
+ pnpm: config.pnpm,
20
+ revision: config.starter,
21
+ skillsCli: config.skillsCli,
22
+ version: manifest.version,
23
+ });
24
+ export const { skills } = config;
25
+ export const presets = {
26
+ desktop: 'Web foundation and Tauri desktop',
27
+ full: 'Web, Tauri desktop and shared-Swift mobile',
28
+ mobile: 'Web foundation with SwiftUI and Jetpack Compose apps',
29
+ web: 'SvelteKit, Rust API and PostgreSQL',
30
+ };
31
+ export class Issue extends Error {
32
+ details;
33
+ code;
34
+ constructor(message, details = {}, code = 1) {
35
+ super(message);
36
+ this.details = details;
37
+ this.code = code;
38
+ }
39
+ }
40
+ export function isUnattended() {
41
+ return isCI || !process.stdin.isTTY || !process.stdout.isTTY || process.env.TERM === 'dumb';
42
+ }
43
+ function redact(value) {
44
+ let clean = stripVTControlCharacters(value);
45
+ for (const [name, secret] of Object.entries(process.env)) {
46
+ if (secret !== undefined && secret.length >= 8 && /(?:api.?key|password|secret|token)/iv.test(name)) {
47
+ clean = clean.replaceAll(secret, '[redacted]');
48
+ }
49
+ }
50
+ return clean
51
+ .replaceAll(/(\w+:\/\/)[^\/\s@]+@/gv, '$1[redacted]@')
52
+ .replaceAll(/\b(?:npm_|gh[pousr]_)[\w]{20,}/gv, '[redacted]')
53
+ .replaceAll(/([Aa]uthorization:\s*(?:[Bb]earer|[Bb]asic)\s+)\S+/gv, '$1[redacted]');
54
+ }
55
+ export class Workflow {
56
+ controller = new AbortController();
57
+ destination;
58
+ installedSkills = [];
59
+ operation;
60
+ settings;
61
+ stage = 'arguments';
62
+ starterRevision = release.revision;
63
+ versions = { node: process.versions.node };
64
+ constructor(operation) {
65
+ this.operation = operation;
66
+ }
67
+ checkCancelled() {
68
+ if (this.controller.signal.aborted)
69
+ throw new Issue('Cancelled.', {}, 130);
70
+ }
71
+ async command(binary, args, options) {
72
+ const { cwd, deliverable } = options;
73
+ const result = await execa(binary, args, {
74
+ cancelSignal: options.signal ?? this.controller.signal,
75
+ cwd,
76
+ env: {
77
+ CI: 'true',
78
+ FORCE_COLOR: undefined,
79
+ GIT_TERMINAL_PROMPT: '0',
80
+ NO_COLOR: '1',
81
+ // `npm exec --package=@divithselvam/jokebook` exports this to the CLI.
82
+ // If it reaches the nested `npx skills@...` call, npx tries to run the
83
+ // outer package instead of the requested skills CLI.
84
+ npm_config_package: undefined,
85
+ },
86
+ reject: false,
87
+ stdin: 'ignore',
88
+ timeout: 300_000,
89
+ });
90
+ if (result.failed) {
91
+ const errorOutput = (result.stderr === '' ? result.stdout === '' ? result.shortMessage : result.stdout : result.stderr) ?? '';
92
+ const code = result.isCanceled ? 130 : 1;
93
+ throw new Issue(result.isCanceled ? 'Cancelled.' : `Could not complete ${deliverable}.`, {
94
+ command: redact(result.escapedCommand),
95
+ cwd,
96
+ deliverable,
97
+ exitCode: result.exitCode ?? null,
98
+ signal: result.signal ?? null,
99
+ stderr: redact(errorOutput),
100
+ stdout: redact(result.stdout ?? ''),
101
+ versions: this.versions,
102
+ }, code);
103
+ }
104
+ return result.stdout;
105
+ }
106
+ async prerequisites(cwd, hasSkills = false) {
107
+ this.stage = 'prerequisites';
108
+ if (process.versions.node !== release.node) {
109
+ throw new Issue(`Use Node.js ${release.node}. Found ${process.versions.node}.`);
110
+ }
111
+ const pnpm = await this.command('pnpm', ['--version'], {
112
+ cwd, deliverable: `pnpm ${release.pnpm} availability`,
113
+ });
114
+ this.versions.pnpm = pnpm;
115
+ if (pnpm !== release.pnpm)
116
+ throw new Issue(`Use pnpm ${release.pnpm}. Found ${pnpm}.`);
117
+ if (hasSkills) {
118
+ this.versions.npm = await this.command('npx', ['--version'], { cwd, deliverable: 'npm/npx availability' });
119
+ this.versions.git = await this.command('git', ['--version'], { cwd, deliverable: 'Git availability' });
120
+ this.versions.skills = release.skillsCli;
121
+ }
122
+ }
123
+ async report(isJson, usage, task, format) {
124
+ const cancel = () => { this.controller.abort(); };
125
+ process.on('SIGINT', cancel);
126
+ process.on('SIGTERM', cancel);
127
+ try {
128
+ const result = await task();
129
+ const data = { ...summarize(this), ...result, ok: true };
130
+ console.log(isJson ? JSON.stringify(data) : format(result));
131
+ }
132
+ catch (error) {
133
+ const issue = error instanceof Issue ? error : new Issue(error instanceof Error ? error.message : String(error));
134
+ const details = { message: redact(issue.message), ...issue.details };
135
+ if (isJson) {
136
+ console.log(JSON.stringify({ ...summarize(this), error: details, ok: false, usage }));
137
+ }
138
+ else {
139
+ console.error(`[${this.stage}] ${details.message}`);
140
+ for (const [key, value] of Object.entries(issue.details)) {
141
+ if (value !== '' && value !== null)
142
+ console.error(`${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`);
143
+ }
144
+ if (issue.code !== 130)
145
+ console.error(usage);
146
+ }
147
+ process.exitCode = issue.code;
148
+ }
149
+ finally {
150
+ process.off('SIGINT', cancel);
151
+ process.off('SIGTERM', cancel);
152
+ }
153
+ }
154
+ }
155
+ function summarize(workflow) {
156
+ return {
157
+ destination: workflow.destination,
158
+ installedSkills: workflow.installedSkills,
159
+ operation: workflow.operation,
160
+ settings: workflow.settings,
161
+ stage: workflow.stage,
162
+ starterRevision: workflow.starterRevision,
163
+ };
164
+ }
165
+ export async function assertDestination(destination) {
166
+ try {
167
+ const entry = await lstat(destination);
168
+ if (!entry.isDirectory() || (await readdir(destination)).length > 0) {
169
+ throw new Issue('Choose a destination that is absent or an empty directory.');
170
+ }
171
+ }
172
+ catch (error) {
173
+ if (error.code !== 'ENOENT')
174
+ throw error;
175
+ }
176
+ }
177
+ export async function resolveDestination(directory) {
178
+ const absolute = path.resolve(directory);
179
+ const { base, dir, root } = path.parse(absolute);
180
+ if (absolute === root || base === '')
181
+ throw new Issue('Choose a destination inside an existing parent directory.');
182
+ const parent = await realpath(dir);
183
+ const destination = path.resolve(parent, base);
184
+ await assertDestination(destination);
185
+ return destination;
186
+ }
187
+ export function packageFile(relative) {
188
+ return fileURLToPath(new URL(relative, import.meta.url));
189
+ }
190
+ export async function readJson(file) {
191
+ return JSON.parse(await readFile(file, 'utf8'));
192
+ }
193
+ export async function findProduct(start = process.cwd()) {
194
+ try {
195
+ const productManifest = await readJson(path.resolve(start, 'package.json'));
196
+ if (productManifest.jokebook?.starter && productManifest.jokebook.stackSha256) {
197
+ return { cwd: start, marker: productManifest.jokebook };
198
+ }
199
+ }
200
+ catch (error) {
201
+ if (error.code !== 'ENOENT')
202
+ throw error;
203
+ }
204
+ const parent = path.dirname(start);
205
+ return parent === start ? undefined : findProduct(parent);
206
+ }
207
+ async function readCatalog(file) {
208
+ try {
209
+ return await readFile(file, 'utf8');
210
+ }
211
+ catch (error) {
212
+ if (error.code === 'ENOENT') {
213
+ throw new Issue('The bundled catalog is missing from this package. Reinstall Jokebook or run npm run build.');
214
+ }
215
+ throw error;
216
+ }
217
+ }
218
+ export async function catalogDocument(product) {
219
+ if (product) {
220
+ let text;
221
+ try {
222
+ text = await readFile(path.resolve(product.cwd, 'STACK.md'), 'utf8');
223
+ }
224
+ catch (error) {
225
+ if (error.code === 'ENOENT') {
226
+ throw new Issue('STACK.md is missing from this product. Restore the catalog recorded in package.json before continuing.');
227
+ }
228
+ throw error;
229
+ }
230
+ const digest = createHash('sha256').update(text).digest('hex');
231
+ if (digest !== product.marker.stackSha256) {
232
+ throw new Issue('STACK.md differs from the recorded revision. Restore the original catalog before continuing.');
233
+ }
234
+ return { digest, text };
235
+ }
236
+ const index = await readJson(packageFile('../dist/catalog/index.json')).catch((error) => {
237
+ if (error.code === 'ENOENT') {
238
+ throw new Issue('The bundled catalog index is missing from this package. Reinstall Jokebook or run npm run build.');
239
+ }
240
+ throw error;
241
+ });
242
+ if (index.catalog !== release.catalog) {
243
+ throw new Issue(`The bundled catalog is ${index.catalog}, but this CLI requires ${release.catalog}. Reinstall Jokebook.`);
244
+ }
245
+ const text = await readCatalog(packageFile('../dist/catalog/STACK.md'));
246
+ const digest = createHash('sha256').update(text).digest('hex');
247
+ if (digest !== index.sha256) {
248
+ throw new Issue('The bundled catalog does not match its recorded SHA-256. Reinstall Jokebook.');
249
+ }
250
+ return { digest, text };
251
+ }
252
+ export function slug(value) {
253
+ return value.toLowerCase().replaceAll(/[^a-z0-9]+/gv, '-').replaceAll(/^-|-$/gv, '');
254
+ }
@@ -0,0 +1,14 @@
1
+ import { type Preset } from './index.js';
2
+ export type StarterIndex = {
3
+ catalog: string;
4
+ catalogSha256: string;
5
+ current: string;
6
+ revisions: string[];
7
+ surfaces: Record<string, string[]>;
8
+ };
9
+ export declare function starterIndex(): Promise<StarterIndex>;
10
+ export declare function starterArchive(revision: string, surface: string): string;
11
+ export declare function extractStarter(revision: string, preset: Preset, destination: string): Promise<{
12
+ base: string;
13
+ surfaces: string[];
14
+ }>;
@@ -0,0 +1,38 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { extract } from 'tar';
4
+ import { Issue, packageFile, readJson } from './index.js';
5
+ export async function starterIndex() {
6
+ try {
7
+ return await readJson(packageFile('../dist/starters/index.json'));
8
+ }
9
+ catch (error) {
10
+ if (error.code === 'ENOENT') {
11
+ throw new Issue('The bundled starter index is missing. Reinstall Jokebook or run npm run build.');
12
+ }
13
+ throw error;
14
+ }
15
+ }
16
+ export function starterArchive(revision, surface) {
17
+ return packageFile(`../dist/starters/${revision}/${surface}.tgz`);
18
+ }
19
+ export async function extractStarter(revision, preset, destination) {
20
+ const index = await starterIndex();
21
+ if (!index.revisions.includes(revision)) {
22
+ throw new Issue(`Starter ${revision} is not bundled with this CLI. Available revisions: ${index.revisions.join(', ')}.`);
23
+ }
24
+ const base = preset === 'desktop' || preset === 'full' ? 'desktop' : 'web';
25
+ await mkdir(destination, { recursive: true });
26
+ const surfaces = index.surfaces[revision] ?? [];
27
+ if (!surfaces.includes(base))
28
+ throw new Issue(`Starter ${revision} does not contain the ${base} archive.`);
29
+ await extract({ cwd: destination, file: starterArchive(revision, base), strict: true });
30
+ if (preset === 'mobile' || preset === 'full') {
31
+ if (!surfaces.includes('mobile'))
32
+ throw new Issue(`Starter ${revision} does not contain the mobile overlay.`);
33
+ const apps = path.join(destination, 'apps');
34
+ await mkdir(apps, { recursive: true });
35
+ await extract({ cwd: apps, file: starterArchive(revision, 'mobile'), strict: true });
36
+ }
37
+ return { base, surfaces };
38
+ }
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,21 @@
1
+ {
2
+ "catalog": "1.1.0",
3
+ "catalogSha256": "14f8bf06942076bf593e89e20f6413677fbf8f0cf4aee9151fbe87e604150e17",
4
+ "current": "1.1.0",
5
+ "revisions": [
6
+ "1.0.0",
7
+ "1.1.0"
8
+ ],
9
+ "surfaces": {
10
+ "1.0.0": [
11
+ "desktop",
12
+ "mobile",
13
+ "web"
14
+ ],
15
+ "1.1.0": [
16
+ "desktop",
17
+ "mobile",
18
+ "web"
19
+ ]
20
+ }
21
+ }
@@ -0,0 +1,30 @@
1
+ import { type Product, type ProductMarker } from './index.js';
2
+ type Action = 'add' | 'conflict' | 'merge' | 'remove' | 'update';
3
+ type Content = Uint8Array;
4
+ type Write = {
5
+ content: Content;
6
+ mode: number;
7
+ };
8
+ export type UpgradeAction = {
9
+ action: Action;
10
+ path: string;
11
+ reason?: string;
12
+ };
13
+ export type UpgradePlan = {
14
+ actions: UpgradeAction[];
15
+ catalog: string;
16
+ conflicts: UpgradeAction[];
17
+ from: string;
18
+ marker: ProductMarker;
19
+ preset: string;
20
+ stackSha256: string;
21
+ status: 'blocked' | 'ready' | 'up-to-date';
22
+ to: string;
23
+ warnings: string[];
24
+ writes: Map<string, Write>;
25
+ };
26
+ export type UpgradeResult = Omit<UpgradePlan, 'marker' | 'writes'>;
27
+ export declare function publicPlan(plan: UpgradePlan): UpgradeResult;
28
+ export declare function planUpgrade(product: Product, currentDigest: string): Promise<UpgradePlan>;
29
+ export declare function applyUpgrade(product: Product, plan: UpgradePlan): Promise<string>;
30
+ export {};