@ductape/cli 0.5.7 → 0.5.9

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.
@@ -0,0 +1,411 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { NAME_PATTERN, UI_MANIFEST_FILE } from './manifest.js';
4
+ /** Where a project keeps the UI pieces it writes, and the folder inside it that holds pieces it added from the registry. */
5
+ export const UI_DIR = path.join('ductape', 'ui');
6
+ export const INSTALLED_DIR = 'installed';
7
+ export const pascalCase = (name) => name.split('-').map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join('');
8
+ /** The project a command works in: the linked Ductape project, else the nearest folder with a package.json, else here. */
9
+ export function uiProjectRoot(linkedDir, start = process.cwd()) {
10
+ if (linkedDir)
11
+ return linkedDir;
12
+ let dir = path.resolve(start);
13
+ while (true) {
14
+ if (fs.existsSync(path.join(dir, 'package.json')))
15
+ return dir;
16
+ const parent = path.dirname(dir);
17
+ if (parent === dir)
18
+ return path.resolve(start);
19
+ dir = parent;
20
+ }
21
+ }
22
+ function reactFiles(manifest) {
23
+ const component = pascalCase(manifest.name);
24
+ return {
25
+ 'index.ts': `export { ${component} } from './${component}';\nexport type { ${component}Props } from './${component}';\n`,
26
+ [`${component}.tsx`]: `'use client';
27
+
28
+ import { useQuery } from '@ductape/react';
29
+ import styles from './${component}.module.css';
30
+
31
+ export interface ${component}Props {
32
+ /** App tag of the action this piece reads from, in the consuming product. */
33
+ app: string;
34
+ /** Action tag to run. */
35
+ action: string;
36
+ /** Input for the action, in Ductape's flat format ('body:x', 'query:y', ...). */
37
+ input?: Record<string, unknown>;
38
+ /** Session token issued by the application's backend, when it uses a publishable key. */
39
+ session?: string;
40
+ title?: string;
41
+ }
42
+
43
+ /**
44
+ * Runs one Ductape action through the application's DuctapeProvider and shows the result. The product, environment and
45
+ * key come from that provider, so the same piece works in every application of the workspace.
46
+ */
47
+ export function ${component}({ app, action, input, session, title = '${component}' }: ${component}Props) {
48
+ const { data, isLoading, error, refetch } = useQuery(
49
+ ['ui:${manifest.name}', app, action, JSON.stringify(input ?? {})],
50
+ (client) => client.api.run({ app, action, input, session }),
51
+ );
52
+
53
+ return (
54
+ <section className={styles.root}>
55
+ <header className={styles.header}>
56
+ <h3 className={styles.title}>{title}</h3>
57
+ <button type="button" className={styles.button} onClick={() => void refetch()} disabled={isLoading}>
58
+ Refresh
59
+ </button>
60
+ </header>
61
+ {isLoading ? <p className={styles.muted}>Loading...</p> : null}
62
+ {error ? <p className={styles.error}>{error.message}</p> : null}
63
+ {!isLoading && !error ? <pre className={styles.result}>{JSON.stringify(data?.data ?? null, null, 2)}</pre> : null}
64
+ </section>
65
+ );
66
+ }
67
+ `,
68
+ [`${component}.module.css`]: `/* Consumers restyle a piece through these variables, without editing its source. */
69
+ .root {
70
+ --ui-${manifest.name}-border: #d4d4d8;
71
+ --ui-${manifest.name}-text: inherit;
72
+ --ui-${manifest.name}-muted: #71717a;
73
+ --ui-${manifest.name}-error: #dc2626;
74
+ border: 1px solid var(--ui-${manifest.name}-border);
75
+ border-radius: 8px;
76
+ padding: 12px 16px;
77
+ color: var(--ui-${manifest.name}-text);
78
+ }
79
+ .header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
80
+ .title { margin: 0; font-size: 14px; font-weight: 600; }
81
+ .button { font: inherit; font-size: 12px; cursor: pointer; }
82
+ .muted { color: var(--ui-${manifest.name}-muted); font-size: 13px; }
83
+ .error { color: var(--ui-${manifest.name}-error); font-size: 13px; }
84
+ .result { margin: 8px 0 0; font-size: 12px; overflow: auto; max-height: 320px; }
85
+ `,
86
+ 'README.md': `# ${manifest.name}
87
+
88
+ ${manifest.description ?? ''}
89
+
90
+ \`\`\`tsx
91
+ import { ${component} } from '#ui/${manifest.name}';
92
+
93
+ <${component} app="<app tag>" action="<action tag>" />
94
+ \`\`\`
95
+
96
+ List the actions this piece needs under \`requires.actions\` in ui.json, so \`ductape ui check\` can confirm the consuming product has them.
97
+ `,
98
+ };
99
+ }
100
+ function vueFiles(manifest) {
101
+ const component = pascalCase(manifest.name);
102
+ return {
103
+ 'index.ts': `export { default as ${component} } from './${component}.vue';\n`,
104
+ [`${component}.vue`]: `<script setup lang="ts">
105
+ import { watch } from 'vue';
106
+ import { useQuery } from '@ductape/vue';
107
+
108
+ /**
109
+ * Runs one Ductape action through the application's Ductape plugin and shows the result. The product, environment and key
110
+ * come from that plugin, so the same piece works in every application of the workspace.
111
+ */
112
+ const props = withDefaults(defineProps<{
113
+ /** App tag of the action this piece reads from, in the consuming product. */
114
+ app: string;
115
+ /** Action tag to run. */
116
+ action: string;
117
+ /** Input for the action, in Ductape's flat format ('body:x', 'query:y', ...). */
118
+ input?: Record<string, unknown>;
119
+ /** Session token issued by the application's backend, when it uses a publishable key. */
120
+ session?: string;
121
+ title?: string;
122
+ }>(), { title: '${component}' });
123
+
124
+ const { data, isLoading, error, refetch } = useQuery(
125
+ ['ui:${manifest.name}', props.app, props.action],
126
+ (client) => client.api.run({ app: props.app, action: props.action, input: props.input, session: props.session }),
127
+ );
128
+
129
+ // The composable runs once; run again when the action or its input changes.
130
+ watch(() => [props.app, props.action, JSON.stringify(props.input ?? {}), props.session], () => { void refetch(); });
131
+ </script>
132
+
133
+ <template>
134
+ <section class="root">
135
+ <header class="header">
136
+ <h3 class="title">{{ title }}</h3>
137
+ <button type="button" class="button" :disabled="isLoading" @click="refetch()">Refresh</button>
138
+ </header>
139
+ <p v-if="isLoading" class="muted">Loading...</p>
140
+ <p v-if="error" class="error">{{ error.message }}</p>
141
+ <pre v-if="!isLoading && !error" class="result">{{ JSON.stringify(data?.data ?? null, null, 2) }}</pre>
142
+ </section>
143
+ </template>
144
+
145
+ <style scoped>
146
+ /* Consumers restyle a piece through these variables, without editing its source. */
147
+ .root {
148
+ --ui-${manifest.name}-border: #d4d4d8;
149
+ --ui-${manifest.name}-text: inherit;
150
+ --ui-${manifest.name}-muted: #71717a;
151
+ --ui-${manifest.name}-error: #dc2626;
152
+ border: 1px solid var(--ui-${manifest.name}-border);
153
+ border-radius: 8px;
154
+ padding: 12px 16px;
155
+ color: var(--ui-${manifest.name}-text);
156
+ }
157
+ .header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
158
+ .title { margin: 0; font-size: 14px; font-weight: 600; }
159
+ .button { font: inherit; font-size: 12px; cursor: pointer; }
160
+ .muted { color: var(--ui-${manifest.name}-muted); font-size: 13px; }
161
+ .error { color: var(--ui-${manifest.name}-error); font-size: 13px; }
162
+ .result { margin: 8px 0 0; font-size: 12px; overflow: auto; max-height: 320px; }
163
+ </style>
164
+ `,
165
+ 'README.md': `# ${manifest.name}
166
+
167
+ ${manifest.description ?? ''}
168
+
169
+ \`\`\`vue
170
+ <script setup lang="ts">
171
+ import { ${component} } from '#ui/${manifest.name}';
172
+ </script>
173
+
174
+ <template>
175
+ <${component} app="<app tag>" action="<action tag>" />
176
+ </template>
177
+ \`\`\`
178
+
179
+ The application installs the Ductape plugin once (\`app.use(createDuctape({ ... }))\` from @ductape/vue). List the actions this
180
+ piece needs under \`requires.actions\` in ui.json, so \`ductape ui check\` can confirm the consuming product has them.
181
+ `,
182
+ };
183
+ }
184
+ function javascriptFiles(manifest) {
185
+ const component = pascalCase(manifest.name);
186
+ const tag = `ui-${manifest.name}`;
187
+ return {
188
+ 'index.ts': `export { mount${component} } from './mount';
189
+ export type { ${component}Options, ${component}Handle } from './mount';
190
+ export { ${component}Element, define${component} } from './element';
191
+ `,
192
+ 'mount.ts': `import type { Ductape } from '@ductape/client';
193
+ import styles from './${component}.module.css';
194
+
195
+ export interface ${component}Options {
196
+ /** The application's Ductape client. The product, environment and key come from it. */
197
+ client: Ductape;
198
+ /** App tag of the action this piece reads from, in the consuming product. */
199
+ app: string;
200
+ /** Action tag to run. */
201
+ action: string;
202
+ /** Input for the action, in Ductape's flat format ('body:x', 'query:y', ...). */
203
+ input?: Record<string, unknown>;
204
+ /** Session token issued by the application's backend, when it uses a publishable key. */
205
+ session?: string;
206
+ title?: string;
207
+ }
208
+
209
+ export interface ${component}Handle {
210
+ /** Change any option; the action runs again. */
211
+ update(next: Partial<${component}Options>): void;
212
+ /** Remove everything this piece added and ignore any result still on its way. Safe to call twice. */
213
+ destroy(): void;
214
+ }
215
+
216
+ /**
217
+ * Renders into \`target\` and runs one Ductape action. Plain DOM code: it works in any application, whatever its framework.
218
+ * Call destroy() when the target goes away.
219
+ */
220
+ export function mount${component}(target: HTMLElement, options: ${component}Options): ${component}Handle {
221
+ let current = { title: '${component}', ...options };
222
+ let run = 0;
223
+ let destroyed = false;
224
+
225
+ const root = document.createElement('section');
226
+ root.className = styles.root;
227
+ const header = document.createElement('header');
228
+ header.className = styles.header;
229
+ const title = document.createElement('h3');
230
+ title.className = styles.title;
231
+ const button = document.createElement('button');
232
+ button.type = 'button';
233
+ button.className = styles.button;
234
+ button.textContent = 'Refresh';
235
+ const status = document.createElement('p');
236
+ const result = document.createElement('pre');
237
+ result.className = styles.result;
238
+ header.append(title, button);
239
+ root.append(header, status, result);
240
+ target.append(root);
241
+
242
+ const show = (state: 'loading' | 'error' | 'done', text: string) => {
243
+ status.hidden = state === 'done';
244
+ status.className = state === 'error' ? styles.error : styles.muted;
245
+ status.textContent = state === 'done' ? '' : text;
246
+ result.hidden = state !== 'done';
247
+ result.textContent = state === 'done' ? text : '';
248
+ button.disabled = state === 'loading';
249
+ };
250
+
251
+ const load = async () => {
252
+ const mine = ++run;
253
+ title.textContent = current.title ?? '${component}';
254
+ show('loading', 'Loading...');
255
+ try {
256
+ const response = await current.client.api.run({ app: current.app, action: current.action, input: current.input, session: current.session });
257
+ // A newer run, or destroy(), wins: a late answer never touches the page.
258
+ if (destroyed || mine !== run) return;
259
+ show('done', JSON.stringify(response?.data ?? null, null, 2));
260
+ } catch (error) {
261
+ if (destroyed || mine !== run) return;
262
+ show('error', error instanceof Error ? error.message : String(error));
263
+ }
264
+ };
265
+
266
+ const onRefresh = () => { void load(); };
267
+ button.addEventListener('click', onRefresh);
268
+ void load();
269
+
270
+ return {
271
+ update(next) {
272
+ if (destroyed) return;
273
+ current = { ...current, ...next };
274
+ void load();
275
+ },
276
+ destroy() {
277
+ if (destroyed) return;
278
+ destroyed = true;
279
+ button.removeEventListener('click', onRefresh);
280
+ root.remove();
281
+ },
282
+ };
283
+ }
284
+ `,
285
+ 'element.ts': `import type { Ductape } from '@ductape/client';
286
+ import { mount${component}, type ${component}Handle } from './mount';
287
+
288
+ /**
289
+ * <${tag} app="..." action="..." title="..."> as a custom element. Set its \`client\` property to the application's Ductape
290
+ * client; it mounts when it is in the page with a client, and cleans up when it is removed.
291
+ */
292
+ export class ${component}Element extends HTMLElement {
293
+ static observedAttributes = ['app', 'action', 'title'];
294
+ private handle: ${component}Handle | null = null;
295
+ private ductape: Ductape | null = null;
296
+ private extra: { input?: Record<string, unknown>; session?: string } = {};
297
+
298
+ get client(): Ductape | null { return this.ductape; }
299
+ set client(value: Ductape | null) { this.ductape = value; this.sync(); }
300
+ get input(): Record<string, unknown> | undefined { return this.extra.input; }
301
+ set input(value: Record<string, unknown> | undefined) { this.extra = { ...this.extra, input: value }; this.sync(); }
302
+ get session(): string | undefined { return this.extra.session; }
303
+ set session(value: string | undefined) { this.extra = { ...this.extra, session: value }; this.sync(); }
304
+
305
+ connectedCallback(): void { this.sync(); }
306
+ disconnectedCallback(): void { this.handle?.destroy(); this.handle = null; }
307
+ attributeChangedCallback(): void { this.sync(); }
308
+
309
+ private sync(): void {
310
+ const app = this.getAttribute('app');
311
+ const action = this.getAttribute('action');
312
+ if (!this.isConnected || !this.ductape || !app || !action) return;
313
+ const options = { client: this.ductape, app, action, title: this.getAttribute('title') ?? undefined, ...this.extra };
314
+ if (this.handle) this.handle.update(options);
315
+ else this.handle = mount${component}(this, options);
316
+ }
317
+ }
318
+
319
+ /** Registers <${tag}> (or another tag name) once; calling it again is harmless. */
320
+ export function define${component}(tagName = '${tag}'): void {
321
+ if (!customElements.get(tagName)) customElements.define(tagName, class extends ${component}Element {});
322
+ }
323
+ `,
324
+ [`${component}.module.css`]: `/* Consumers restyle a piece through these variables, without editing its source. */
325
+ .root {
326
+ --ui-${manifest.name}-border: #d4d4d8;
327
+ --ui-${manifest.name}-text: inherit;
328
+ --ui-${manifest.name}-muted: #71717a;
329
+ --ui-${manifest.name}-error: #dc2626;
330
+ display: block;
331
+ border: 1px solid var(--ui-${manifest.name}-border);
332
+ border-radius: 8px;
333
+ padding: 12px 16px;
334
+ color: var(--ui-${manifest.name}-text);
335
+ }
336
+ .header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
337
+ .title { margin: 0; font-size: 14px; font-weight: 600; }
338
+ .button { font: inherit; font-size: 12px; cursor: pointer; }
339
+ .muted { color: var(--ui-${manifest.name}-muted); font-size: 13px; }
340
+ .error { color: var(--ui-${manifest.name}-error); font-size: 13px; }
341
+ .result { margin: 8px 0 0; font-size: 12px; overflow: auto; max-height: 320px; }
342
+ `,
343
+ 'README.md': `# ${manifest.name}
344
+
345
+ ${manifest.description ?? ''}
346
+
347
+ Plain DOM code, so any application can use it: plain JavaScript, React, Vue or anything else.
348
+
349
+ \`\`\`ts
350
+ import { Ductape } from '@ductape/client';
351
+ import { mount${component}, define${component} } from '#ui/${manifest.name}';
352
+
353
+ const client = new Ductape({ accessKey: '<publishable key>', product: '<product>', env: '<env>' });
354
+
355
+ // As a function: you decide when it goes away.
356
+ const handle = mount${component}(document.getElementById('orders')!, { client, app: '<app tag>', action: '<action tag>' });
357
+ handle.destroy();
358
+
359
+ // Or as a custom element: it cleans up when removed from the page.
360
+ define${component}();
361
+ const element = document.createElement('${tag}') as HTMLElement & { client: Ductape };
362
+ element.setAttribute('app', '<app tag>');
363
+ element.setAttribute('action', '<action tag>');
364
+ element.client = client;
365
+ document.body.append(element);
366
+ \`\`\`
367
+
368
+ List the actions this piece needs under \`requires.actions\` in ui.json, so \`ductape ui check\` can confirm the consuming product has them.
369
+ `,
370
+ };
371
+ }
372
+ const PEERS = {
373
+ react: { react: '>=18', '@ductape/react': '>=0.0.7' },
374
+ vue: { vue: '>=3.3', '@ductape/vue': '>=0.0.3' },
375
+ javascript: { '@ductape/client': '>=0.0.5' },
376
+ };
377
+ /** Writes a new UI piece. Refuses to touch a folder that already exists. */
378
+ export function scaffoldUi(projectRoot, name, framework, description) {
379
+ if (!NAME_PATTERN.test(name) || name.length > 64)
380
+ throw new Error('Name must be lowercase words joined by hyphens, such as "order-table"');
381
+ if (name === INSTALLED_DIR)
382
+ throw new Error(`"${INSTALLED_DIR}" is reserved for UI pieces added from the registry`);
383
+ const dir = path.join(projectRoot, UI_DIR, name);
384
+ if (fs.existsSync(dir))
385
+ throw new Error(`${path.relative(projectRoot, dir)} already exists`);
386
+ const manifest = {
387
+ name,
388
+ version: '0.1.0',
389
+ framework,
390
+ entry: 'index.ts',
391
+ ...(description ? { description } : {}),
392
+ peerDependencies: { ...PEERS[framework] },
393
+ requires: { actions: [] },
394
+ };
395
+ const files = { [UI_MANIFEST_FILE]: `${JSON.stringify(manifest, null, 2)}\n`, ...(framework === 'vue' ? vueFiles(manifest) : framework === 'javascript' ? javascriptFiles(manifest) : reactFiles(manifest)) };
396
+ fs.mkdirSync(dir, { recursive: true });
397
+ for (const [file, content] of Object.entries(files))
398
+ fs.writeFileSync(path.join(dir, file), content, { flag: 'wx' });
399
+ return { dir, files: Object.keys(files).sort() };
400
+ }
401
+ /** The UI pieces a project has written: every folder under ductape/ui with a ui.json, except the installed ones. */
402
+ export function listAuthoredUi(projectRoot) {
403
+ const root = path.join(projectRoot, UI_DIR);
404
+ if (!fs.existsSync(root))
405
+ return [];
406
+ return fs.readdirSync(root, { withFileTypes: true })
407
+ .filter((entry) => entry.isDirectory() && entry.name !== INSTALLED_DIR && !entry.name.startsWith('.'))
408
+ .filter((entry) => fs.existsSync(path.join(root, entry.name, UI_MANIFEST_FILE)))
409
+ .map((entry) => entry.name)
410
+ .sort();
411
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Just enough of npm's version ranges to check a UI piece's peerDependencies against what an application has installed:
3
+ * exact versions, comparators, ^, ~, x-ranges, hyphen ranges, spaces (and) and || (or). Anything else, such as
4
+ * "workspace:*" or a git URL, is reported as not understood rather than guessed at.
5
+ */
6
+ type Version = [number, number, number, string[]];
7
+ export declare function parseVersion(value: string): Version | undefined;
8
+ export declare function compareVersions(a: string, b: string): number;
9
+ /** True or false when the range is understood; undefined when it is not. */
10
+ export declare function satisfies(version: string, range: string): boolean | undefined;
11
+ export {};
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Just enough of npm's version ranges to check a UI piece's peerDependencies against what an application has installed:
3
+ * exact versions, comparators, ^, ~, x-ranges, hyphen ranges, spaces (and) and || (or). Anything else, such as
4
+ * "workspace:*" or a git URL, is reported as not understood rather than guessed at.
5
+ */
6
+ const VERSION = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
7
+ const PARTIAL = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?$/;
8
+ export function parseVersion(value) {
9
+ const m = VERSION.exec(value.trim());
10
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? m[4].split('.') : []] : undefined;
11
+ }
12
+ export function compareVersions(a, b) {
13
+ const x = parseVersion(a);
14
+ const y = parseVersion(b);
15
+ if (!x || !y)
16
+ throw new Error(`Not a version: ${!x ? a : b}`);
17
+ return compareParsed(x, y);
18
+ }
19
+ function compareParsed(x, y) {
20
+ for (let i = 0; i < 3; i += 1)
21
+ if (x[i] !== y[i])
22
+ return x[i] - y[i];
23
+ const [p, q] = [x[3], y[3]];
24
+ if (p.length === 0 || q.length === 0)
25
+ return q.length - p.length;
26
+ for (let i = 0; i < Math.max(p.length, q.length); i += 1) {
27
+ if (p[i] === undefined)
28
+ return -1;
29
+ if (q[i] === undefined)
30
+ return 1;
31
+ if (p[i] === q[i])
32
+ continue;
33
+ const pn = /^\d+$/.test(p[i]);
34
+ const qn = /^\d+$/.test(q[i]);
35
+ if (pn && qn)
36
+ return Number(p[i]) - Number(q[i]);
37
+ if (pn !== qn)
38
+ return pn ? -1 : 1;
39
+ return p[i] < q[i] ? -1 : 1;
40
+ }
41
+ return 0;
42
+ }
43
+ const num = (part) => (part === undefined || /^[xX*]$/.test(part) ? undefined : Number(part));
44
+ /** The comparators one token stands for, or undefined when the token is not understood. */
45
+ function expand(token) {
46
+ const opMatch = /^(>=|<=|>|<|=|\^|~)?\s*(.*)$/.exec(token);
47
+ const op = opMatch[1] ?? '';
48
+ const m = PARTIAL.exec(opMatch[2]);
49
+ if (!m)
50
+ return undefined;
51
+ const [major, minor, patch] = [num(m[1]), num(m[2]), num(m[3])];
52
+ const pre = m[4] ? m[4].split('.') : [];
53
+ if (major === undefined)
54
+ return op === '<' || op === '>' ? [{ op: '<', v: [0, 0, 0, ['0']] }] : [];
55
+ const lo = [major, minor ?? 0, patch ?? 0, pre];
56
+ const bumped = (level) => (level === 0 ? [major + 1, 0, 0, ['0']] : level === 1 ? [major, (minor ?? 0) + 1, 0, ['0']] : [major, minor ?? 0, (patch ?? 0) + 1, ['0']]);
57
+ const bump = bumped;
58
+ const upper = (level) => ({ op: '<', v: bumped(level), bound: true });
59
+ const partialLevel = minor === undefined ? 0 : patch === undefined ? 1 : undefined;
60
+ switch (op) {
61
+ case '^': {
62
+ const level = major > 0 || minor === undefined ? 0 : (minor ?? 0) > 0 || patch === undefined ? 1 : 2;
63
+ return [{ op: '>=', v: lo }, upper(level)];
64
+ }
65
+ case '~':
66
+ return [{ op: '>=', v: lo }, upper(minor === undefined ? 0 : 1)];
67
+ case '>':
68
+ return partialLevel === undefined ? [{ op: '>', v: lo }] : [{ op: '>=', v: bump(partialLevel), bound: true }];
69
+ case '<=':
70
+ return partialLevel === undefined ? [{ op: '<=', v: lo }] : [upper(partialLevel)];
71
+ case '>=':
72
+ case '<':
73
+ return [{ op, v: lo }];
74
+ default:
75
+ return partialLevel === undefined ? [{ op: '=', v: lo }] : [{ op: '>=', v: lo }, upper(partialLevel)];
76
+ }
77
+ }
78
+ function holds(v, c) {
79
+ const d = compareParsed(v, c.v);
80
+ return c.op === '>=' ? d >= 0 : c.op === '>' ? d > 0 : c.op === '<' ? d < 0 : c.op === '<=' ? d <= 0 : d === 0;
81
+ }
82
+ /** True or false when the range is understood; undefined when it is not. */
83
+ export function satisfies(version, range) {
84
+ const v = parseVersion(version);
85
+ if (!v)
86
+ return undefined;
87
+ const sets = range.trim() === '' ? [''] : range.split('||');
88
+ let understood = true;
89
+ for (const raw of sets) {
90
+ const set = raw.trim();
91
+ const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(set);
92
+ const tokens = hyphen ? [`>=${hyphen[1]}`, `<=${hyphen[2]}`] : set.replace(/(>=|<=|>|<|=|\^|~)\s+/g, '$1').split(/\s+/).filter(Boolean);
93
+ const comparators = [];
94
+ let ok = true;
95
+ for (const token of tokens) {
96
+ const expanded = expand(token);
97
+ if (!expanded) {
98
+ ok = false;
99
+ break;
100
+ }
101
+ comparators.push(...expanded);
102
+ }
103
+ if (!ok) {
104
+ understood = false;
105
+ continue;
106
+ }
107
+ if (!comparators.every((c) => holds(v, c)))
108
+ continue;
109
+ // As npm does: a pre-release only satisfies a range that names a pre-release of the same version.
110
+ if (v[3].length > 0 && !comparators.some((c) => !c.bound && c.v[3].length > 0 && c.v[0] === v[0] && c.v[1] === v[1] && c.v[2] === v[2]))
111
+ continue;
112
+ return true;
113
+ }
114
+ return understood ? false : undefined;
115
+ }
@@ -0,0 +1,33 @@
1
+ import { type IUiDiagnostic, type IUiManifest } from './manifest.js';
2
+ import { type IUiPack } from './pack.js';
3
+ export interface IUiValidation {
4
+ ok: boolean;
5
+ dir: string;
6
+ manifest?: IUiManifest;
7
+ files: string[];
8
+ diagnostics: IUiDiagnostic[];
9
+ }
10
+ /** The package an import names: "react" for "react/jsx-runtime", "@ductape/react" for "@ductape/react/x". */
11
+ export declare function packageOf(specifier: string): string;
12
+ interface ICollected {
13
+ files: Array<{
14
+ path: string;
15
+ content: string;
16
+ }>;
17
+ diagnostics: IUiDiagnostic[];
18
+ }
19
+ /** Reads every file that would be published, refusing links, binaries and anything over the size limits. */
20
+ export declare function collectUiFiles(dir: string): ICollected;
21
+ /** Checks one UI piece's directory: its manifest, the files that would be published and what its code imports. */
22
+ export declare function validateUiDirectory(dir: string): IUiValidation;
23
+ /** Validates and, only when there is nothing wrong, packs. */
24
+ export declare function packUiDirectory(dir: string): {
25
+ validation: IUiValidation;
26
+ pack?: IUiPack;
27
+ };
28
+ /**
29
+ * Type-checks a UI piece with the TypeScript and type packages of the project it is written in, so it compiles against
30
+ * the React and Ductape SDK versions that project has. Other UI pieces it uses resolve from ductape/ui.
31
+ */
32
+ export declare function typecheckUiDirectory(dir: string, projectRoot: string): IUiDiagnostic[];
33
+ export {};