@motionskit/cli 0.2.0 → 0.2.3

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @motionskit/cli
2
2
 
3
- `motions init`, `check`, `test`, `push`, `pull` and `open`.
3
+ `motions init`, `check`, `test`, `push`, `pull`, `open` and `retry`.
4
4
 
5
5
  From a directory with `tenant.yaml`, `motions push` publishes a draft and prints a link. `motions push --live` makes it the version new batches open on. `MOTIONS_URL` defaults to `http://localhost:8787`. `MOTIONS_TOKEN` is an API key (`mot_…`) sent as `authorization: Bearer`.
6
6
 
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/compile.ts
2
2
  import { createHash as createHash2 } from "crypto";
3
3
  import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
4
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve2, sep as sep2 } from "path";
4
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join4, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
5
5
  import { fileURLToPath } from "url";
6
6
  import {
7
7
  CRM_WRITES,
@@ -263,9 +263,70 @@ function ttlSeconds(ttl) {
263
263
  const ms = typeof ttl === "string" ? parseDuration2(ttl) : null;
264
264
  return ms === null ? `ttl must be a duration such as "7d" or "12h", or seconds, got ${JSON.stringify(ttl)}` : Math.round(ms / 1e3);
265
265
  }
266
+ var PACE_KEYS = /* @__PURE__ */ new Set(["requests", "per", "concurrency"]);
267
+ function parsePaceMs(per) {
268
+ if (typeof per === "number") return Number.isInteger(per) && per > 0 ? per : `per must be a positive integer in ms or a duration such as "1s", got ${per}`;
269
+ if (typeof per === "string") {
270
+ const msMatch = /^(\d+)\s*ms$/.exec(per.trim());
271
+ if (msMatch) return Number(msMatch[1]);
272
+ const ms = parseDuration2(per);
273
+ if (ms !== null) return ms;
274
+ }
275
+ return `per must be a duration such as "1s" or "10s", or milliseconds, got ${JSON.stringify(per)}`;
276
+ }
277
+ function isInlinePaceSpec(v) {
278
+ const keys = Object.keys(v);
279
+ return keys.length > 0 && keys.every((k) => PACE_KEYS.has(k)) && keys.every((k) => typeof v[k] !== "object" || v[k] === null);
280
+ }
281
+ function normalizeBucketSpec(where2, raw, errors) {
282
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
283
+ errors.push(`${where2}: pace must be an object`);
284
+ return null;
285
+ }
286
+ const obj = raw;
287
+ const extra = Object.keys(obj).filter((k) => !PACE_KEYS.has(k));
288
+ if (extra.length) {
289
+ errors.push(`${where2}: unknown pace field${extra.length > 1 ? "s" : ""} ${extra.join(", ")}`);
290
+ return null;
291
+ }
292
+ const spec = {};
293
+ if (obj.requests !== void 0) spec.requests = obj.requests;
294
+ if (obj.per !== void 0) {
295
+ const perMs = parsePaceMs(obj.per);
296
+ if (typeof perMs === "string") {
297
+ errors.push(`${where2}: ${perMs}`);
298
+ return null;
299
+ }
300
+ spec.perMs = perMs;
301
+ }
302
+ if (obj.concurrency !== void 0) spec.concurrency = obj.concurrency;
303
+ return spec;
304
+ }
305
+ function normalizeSourcePace(raw, errors) {
306
+ if (raw === void 0) return {};
307
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
308
+ errors.push("pace must be a bucket spec or a map of named buckets");
309
+ return {};
310
+ }
311
+ const obj = raw;
312
+ if (!Object.keys(obj).length) {
313
+ errors.push("pace must declare at least one bucket");
314
+ return {};
315
+ }
316
+ if (isInlinePaceSpec(obj)) {
317
+ const spec = normalizeBucketSpec("bucket default", obj, errors);
318
+ return spec ? { default: spec } : {};
319
+ }
320
+ const out = {};
321
+ for (const [name, entry] of Object.entries(obj)) {
322
+ const spec = normalizeBucketSpec(`bucket ${name}`, entry, errors);
323
+ if (spec) out[name] = spec;
324
+ }
325
+ return out;
326
+ }
266
327
  async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
267
328
  const tenantDir = resolve(tenantRoot);
268
- const id2 = dir.split(sep).at(-1);
329
+ const id2 = folderName(dir);
269
330
  const where2 = `${tenant}/sources/${id2}`;
270
331
  const root = resolve(dir);
271
332
  const index = join3(root, "index.ts");
@@ -286,6 +347,8 @@ async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
286
347
  if (def?.kind !== "source") throw new SourceErrors(where2, ["index.ts must `export default defineSource({ \u2026 })`"]);
287
348
  const errors = [];
288
349
  if (def.id !== id2) errors.push(`the source's id "${def.id}" must match its folder, sources/${id2}`);
350
+ const buckets = normalizeSourcePace(def.pace, errors);
351
+ const hasDefaultBucket = Object.hasOwn(buckets, "default");
289
352
  const ops = {};
290
353
  for (const [name, op] of Object.entries(def.ops ?? {})) {
291
354
  if (!op?.input || typeof op.input !== "object" || !("~standard" in op.input))
@@ -293,7 +356,25 @@ async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
293
356
  if (typeof op?.call !== "function") errors.push(`op ${name}: call must be a function`);
294
357
  const ttl = ttlSeconds(op?.ttl);
295
358
  if (typeof ttl === "string") errors.push(`op ${name}: ${ttl}`);
296
- ops[name] = { ttlSeconds: typeof ttl === "number" ? ttl : 0 };
359
+ let opBuckets;
360
+ if (op?.pace === void 0) {
361
+ if (hasDefaultBucket) opBuckets = ["default"];
362
+ } else if (op.pace === false) {
363
+ opBuckets = void 0;
364
+ } else if (Array.isArray(op.pace)) {
365
+ if (!op.pace.length || op.pace.some((b) => typeof b !== "string")) errors.push(`op ${name}: pace list must be a non-empty array of bucket names`);
366
+ else opBuckets = [...op.pace];
367
+ } else if (typeof op.pace === "object" && op.pace !== null) {
368
+ const bucketKey = Object.hasOwn(buckets, name) ? `op_${name}` : name;
369
+ const spec = normalizeBucketSpec(`op ${name}`, op.pace, errors);
370
+ if (spec) {
371
+ buckets[bucketKey] = spec;
372
+ opBuckets = [bucketKey];
373
+ }
374
+ } else {
375
+ errors.push(`op ${name}: pace must be false, a list of bucket names, or { requests, per, concurrency }`);
376
+ }
377
+ ops[name] = { ttlSeconds: typeof ttl === "number" ? ttl : 0, ...opBuckets ? { buckets: opBuckets } : {} };
297
378
  }
298
379
  const out = await build(
299
380
  options(
@@ -313,6 +394,7 @@ export default serveSource(def);
313
394
  title: yaml.data?.title ?? def.title ?? id2,
314
395
  hosts: [...def.hosts ?? []],
315
396
  secrets: [...def.secrets ?? []],
397
+ ...Object.keys(buckets).length ? { buckets } : {},
316
398
  ops,
317
399
  bundle: sha256(bundle2)
318
400
  };
@@ -351,11 +433,15 @@ function monorepoTenants() {
351
433
  if (!existsSync3(dir)) return null;
352
434
  return readdirSync3(dir).filter((name) => !name.startsWith(".") && existsSync3(join4(dir, name, "tenant.yaml"))).sort().map((name) => join4(dir, name));
353
435
  }
436
+ function folderName(dir) {
437
+ const leaf = win32.basename(win32.normalize(dir));
438
+ return leaf !== "." && leaf !== ".." ? leaf : win32.basename(resolve2(dir));
439
+ }
354
440
  function tenantIdentity(dir) {
355
441
  const meta = readYaml(join4(dir, "tenant.yaml")) ?? {};
356
442
  const motionsDir = join4(dir, "motions");
357
443
  const motions = existsSync3(motionsDir) ? readdirSync3(motionsDir).filter((name) => existsSync3(join4(motionsDir, name, "motion.yaml"))).sort() : [];
358
- return { id: meta.id ?? basename(dir), motions };
444
+ return { id: meta.id ?? folderName(dir), motions };
359
445
  }
360
446
  var tenantsDir = () => {
361
447
  const dir = resolve2(dirname2(fileURLToPath(import.meta.url)), "../../..", "tenants");
@@ -387,7 +473,8 @@ var MotionErrors = class extends Error {
387
473
  async function compileMotion(tenant, dir) {
388
474
  const tenantDir = findTenantDir(dir);
389
475
  if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
390
- const where2 = `${tenant.id}/${dir.split("/").at(-1)}/motion.yaml`;
476
+ const folder = folderName(dir);
477
+ const where2 = `${tenant.id}/${folder}/motion.yaml`;
391
478
  const parsed = parseMotion(readYaml(join4(dir, "motion.yaml")));
392
479
  if (!parsed.ok) throw new MotionErrors(where2, parsed.errors);
393
480
  const raw = parsed.motion;
@@ -426,10 +513,11 @@ async function compileMotion(tenant, dir) {
426
513
  for (const [id2, q] of Object.entries(raw.queues ?? {})) {
427
514
  queues[id2] = { title: q.title, owner: q.owner ?? approvers[0] ?? "operator", deadline: q.deadline, default: q.default ?? "hold" };
428
515
  }
516
+ const motion = raw.motion ?? folder;
429
517
  const manifest = {
430
518
  tenant: tenant.id,
431
- motion: raw.motion ?? dir.split("/").at(-1),
432
- title: raw.title ?? raw.motion ?? dir,
519
+ motion,
520
+ title: raw.title ?? motion,
433
521
  timezone: raw.timezone ?? tenant.timezone,
434
522
  calendar: raw.calendar ?? {},
435
523
  approvers,
@@ -456,7 +544,7 @@ function compileInput(input) {
456
544
  async function compileTenant(tenantDir) {
457
545
  const dir = resolve2(tenantDir);
458
546
  const meta = readYaml(join4(dir, "tenant.yaml")) ?? {};
459
- const id2 = meta.id ?? dir.split("/").filter(Boolean).at(-1);
547
+ const id2 = meta.id ?? folderName(tenantDir);
460
548
  const timezone = meta.timezone ?? "America/Sao_Paulo";
461
549
  const connection = readYaml(join4(dir, "crm.yaml"));
462
550
  const seedPath = join4(dir, "crm-seed.json");
package/dist/main.js CHANGED
@@ -1,11 +1,104 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/main.ts
4
- import { spawnSync } from "child_process";
5
- import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
6
- import { dirname as dirname5, join as join8, resolve as resolve5, sep as sep4 } from "path";
4
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4 } from "fs";
5
+ import { dirname as dirname6, join as join9, resolve as resolve6 } from "path";
7
6
  import { parseArgs } from "util";
8
7
 
8
+ // src/batches.ts
9
+ function matchMotionsList(lists, query) {
10
+ const byId = lists.find((l) => l.id === query);
11
+ if (byId) return byId;
12
+ const exact = lists.filter((l) => l.name === query);
13
+ if (exact.length === 1) return exact[0];
14
+ if (exact.length > 1) {
15
+ throw new Error(`"${query}" matches ${exact.length} Motions lists (${exact.map((l) => l.id).join(", ")}); pass the list id`);
16
+ }
17
+ const folded = query.trim().toLowerCase();
18
+ const byName = lists.filter((l) => l.name.trim().toLowerCase() === folded);
19
+ if (byName.length === 1) return byName[0];
20
+ if (byName.length > 1) {
21
+ throw new Error(`"${query}" matches ${byName.length} Motions lists (${byName.map((l) => l.id).join(", ")}); pass the list id`);
22
+ }
23
+ return null;
24
+ }
25
+ async function openBatch(call, input) {
26
+ if (input.list !== void 0 && input.companies !== void 0) {
27
+ throw new Error("pass --list or --companies, not both");
28
+ }
29
+ if (input.again && input.list === void 0) {
30
+ throw new Error("--again requires --list <id-or-name>");
31
+ }
32
+ const base = `/api/tenants/${encodeURIComponent(input.tenant)}`;
33
+ const body = {};
34
+ if (input.label !== void 0) body.label = input.label;
35
+ if (input.companies !== void 0) {
36
+ const ids = input.companies.split(",").map((s) => s.trim()).filter(Boolean);
37
+ if (!ids.length) throw new Error("--companies needs at least one company id");
38
+ body.companies = ids;
39
+ } else if (input.list !== void 0) {
40
+ const query = input.list.trim();
41
+ if (!query) throw new Error("--list needs a list id or name");
42
+ const { lists } = await call(`${base}/lists`, void 0, input.tenant);
43
+ const matched = matchMotionsList(lists, query);
44
+ if (matched) {
45
+ body.fromList = { id: matched.id, ...input.again ? { again: true } : {} };
46
+ } else {
47
+ if (input.again) throw new Error(`no Motions list "${query}" in ${input.tenant}; --again only applies to Motions lists`);
48
+ body.list = query;
49
+ }
50
+ }
51
+ return call(`${base}/motions/${encodeURIComponent(input.motion)}/batches`, body, input.tenant);
52
+ }
53
+ function isStoppedOrFailed(cell) {
54
+ if (!cell || cell.fenced) return false;
55
+ return cell.state === "failed" || cell.state === "parked" && cell.nextAt === void 0;
56
+ }
57
+ function runnableSteps(motion) {
58
+ return new Set(motion.steps.filter((s) => s.kind === "company" || s.kind === "batch").map((s) => s.id));
59
+ }
60
+ function findCompany(companies, query) {
61
+ return companies.find((c) => c.key === query) ?? companies.find((c) => c.key.endsWith(`:${query}`));
62
+ }
63
+ function selectRetries(snap, batch, options2 = {}) {
64
+ const runnable = runnableSteps(snap.motion);
65
+ const step2 = options2.step?.trim();
66
+ const company = options2.company?.trim();
67
+ if (step2 !== void 0) {
68
+ if (!step2) throw new Error("--step needs a step id");
69
+ if (!runnable.has(step2)) throw new Error(`${step2} is not a runnable step in ${snap.motion.motion}`);
70
+ }
71
+ if (company !== void 0) {
72
+ if (!company) throw new Error("--company needs a company id");
73
+ const found = findCompany(snap.status.companies, company);
74
+ if (!found) throw new Error(`no company ${company} in ${batch}`);
75
+ if (step2) {
76
+ if (found.cells[step2]?.fenced) throw new Error(`${found.key} is already sealed past ${step2} in ${batch}`);
77
+ return [{ company: found.key, step: step2 }];
78
+ }
79
+ const steps = snap.motion.steps.filter((s) => runnable.has(s.id) && isStoppedOrFailed(found.cells[s.id])).map((s) => s.id);
80
+ if (!steps.length) throw new Error(`${found.key} has no failed or stopped step in ${batch}; pass --step <id>`);
81
+ return steps.map((s) => ({ company: found.key, step: s }));
82
+ }
83
+ const ordered = step2 ? [step2] : snap.motion.steps.filter((s) => runnable.has(s.id)).map((s) => s.id);
84
+ const out = [];
85
+ for (const c of snap.status.companies) {
86
+ for (const s of ordered) {
87
+ if (isStoppedOrFailed(c.cells[s])) out.push({ company: c.key, step: s });
88
+ }
89
+ }
90
+ return out;
91
+ }
92
+ async function retryBatch(call, input) {
93
+ const snap = await call(`/api/batches/${encodeURIComponent(input.batch)}`, void 0, input.tenant);
94
+ const tenant = snap.status.tenant;
95
+ const targets = selectRetries(snap, input.batch, { company: input.company, step: input.step });
96
+ for (const target of targets) {
97
+ await call(`/api/batches/${encodeURIComponent(input.batch)}/retry`, target, tenant);
98
+ }
99
+ return { tenant, retried: targets };
100
+ }
101
+
9
102
  // src/client.ts
10
103
  import { existsSync, readFileSync } from "fs";
11
104
  import { dirname, join } from "path";
@@ -23,9 +116,9 @@ function tokenFiles() {
23
116
  }
24
117
  return files;
25
118
  }
26
- function tokenFor(tenant, url2) {
119
+ function tokenFor(tenant, url2, batch) {
27
120
  if (process.env.MOTIONS_TOKEN) return process.env.MOTIONS_TOKEN;
28
- if (!tenant) return void 0;
121
+ if (!tenant && !batch) return void 0;
29
122
  let hostname;
30
123
  try {
31
124
  hostname = new URL(url2).hostname;
@@ -36,8 +129,16 @@ function tokenFor(tenant, url2) {
36
129
  for (const file2 of tokenFiles()) {
37
130
  if (!existsSync(file2)) continue;
38
131
  try {
39
- const key = JSON.parse(readFileSync(file2, "utf8")).tenants?.[tenant];
40
- if (key) return key;
132
+ const tenants = JSON.parse(readFileSync(file2, "utf8")).tenants;
133
+ if (!tenants) continue;
134
+ if (tenant) {
135
+ if (tenants[tenant]) return tenants[tenant];
136
+ continue;
137
+ }
138
+ if (batch) {
139
+ const match = Object.keys(tenants).filter((t) => batch === t || batch.startsWith(`${t}-`)).sort((a, b) => b.length - a.length)[0];
140
+ if (match && tenants[match]) return tenants[match];
141
+ }
41
142
  } catch {
42
143
  }
43
144
  }
@@ -58,9 +159,10 @@ function describeFailure(path, status, text) {
58
159
  if (status === 403) return code ? `forbidden (${code}): ${message}` : `forbidden: ${message}`;
59
160
  return `${path} \u2192 ${status}${code ? ` ${code}` : ""}: ${message}`;
60
161
  }
61
- async function api(url2, path, body) {
62
- const tenant = path.match(/\/api\/tenants\/([^/]+)/)?.[1];
63
- const key = tokenFor(tenant, url2);
162
+ async function api(url2, path, body, tenant) {
163
+ const pathTenant = tenant ?? path.match(/\/api\/tenants\/([^/]+)/)?.[1];
164
+ const batch = pathTenant ? void 0 : path.match(/\/api\/batches\/([^/?#]+)/)?.[1];
165
+ const key = tokenFor(pathTenant ? decodeURIComponent(pathTenant) : void 0, url2, batch ? decodeURIComponent(batch) : void 0);
64
166
  const headers = { accept: "application/json", ...key ? { authorization: `Bearer ${key}` } : {} };
65
167
  if (body !== void 0) headers["content-type"] = "application/json";
66
168
  const res = await fetch(`${url2.replace(/\/$/, "")}${path}`, {
@@ -76,7 +178,7 @@ async function api(url2, path, body) {
76
178
  // src/compile.ts
77
179
  import { createHash as createHash2 } from "crypto";
78
180
  import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync4 } from "fs";
79
- import { basename, dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve2, sep as sep2 } from "path";
181
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5, relative as relative2, resolve as resolve2, sep as sep2, win32 } from "path";
80
182
  import { fileURLToPath as fileURLToPath2 } from "url";
81
183
  import {
82
184
  CRM_WRITES,
@@ -350,9 +452,70 @@ function ttlSeconds(ttl) {
350
452
  const ms = typeof ttl === "string" ? parseDuration2(ttl) : null;
351
453
  return ms === null ? `ttl must be a duration such as "7d" or "12h", or seconds, got ${JSON.stringify(ttl)}` : Math.round(ms / 1e3);
352
454
  }
455
+ var PACE_KEYS = /* @__PURE__ */ new Set(["requests", "per", "concurrency"]);
456
+ function parsePaceMs(per) {
457
+ if (typeof per === "number") return Number.isInteger(per) && per > 0 ? per : `per must be a positive integer in ms or a duration such as "1s", got ${per}`;
458
+ if (typeof per === "string") {
459
+ const msMatch = /^(\d+)\s*ms$/.exec(per.trim());
460
+ if (msMatch) return Number(msMatch[1]);
461
+ const ms = parseDuration2(per);
462
+ if (ms !== null) return ms;
463
+ }
464
+ return `per must be a duration such as "1s" or "10s", or milliseconds, got ${JSON.stringify(per)}`;
465
+ }
466
+ function isInlinePaceSpec(v) {
467
+ const keys = Object.keys(v);
468
+ return keys.length > 0 && keys.every((k) => PACE_KEYS.has(k)) && keys.every((k) => typeof v[k] !== "object" || v[k] === null);
469
+ }
470
+ function normalizeBucketSpec(where2, raw, errors) {
471
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
472
+ errors.push(`${where2}: pace must be an object`);
473
+ return null;
474
+ }
475
+ const obj = raw;
476
+ const extra = Object.keys(obj).filter((k) => !PACE_KEYS.has(k));
477
+ if (extra.length) {
478
+ errors.push(`${where2}: unknown pace field${extra.length > 1 ? "s" : ""} ${extra.join(", ")}`);
479
+ return null;
480
+ }
481
+ const spec = {};
482
+ if (obj.requests !== void 0) spec.requests = obj.requests;
483
+ if (obj.per !== void 0) {
484
+ const perMs = parsePaceMs(obj.per);
485
+ if (typeof perMs === "string") {
486
+ errors.push(`${where2}: ${perMs}`);
487
+ return null;
488
+ }
489
+ spec.perMs = perMs;
490
+ }
491
+ if (obj.concurrency !== void 0) spec.concurrency = obj.concurrency;
492
+ return spec;
493
+ }
494
+ function normalizeSourcePace(raw, errors) {
495
+ if (raw === void 0) return {};
496
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
497
+ errors.push("pace must be a bucket spec or a map of named buckets");
498
+ return {};
499
+ }
500
+ const obj = raw;
501
+ if (!Object.keys(obj).length) {
502
+ errors.push("pace must declare at least one bucket");
503
+ return {};
504
+ }
505
+ if (isInlinePaceSpec(obj)) {
506
+ const spec = normalizeBucketSpec("bucket default", obj, errors);
507
+ return spec ? { default: spec } : {};
508
+ }
509
+ const out = {};
510
+ for (const [name, entry] of Object.entries(obj)) {
511
+ const spec = normalizeBucketSpec(`bucket ${name}`, entry, errors);
512
+ if (spec) out[name] = spec;
513
+ }
514
+ return out;
515
+ }
353
516
  async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
354
517
  const tenantDir = resolve(tenantRoot);
355
- const id2 = dir.split(sep).at(-1);
518
+ const id2 = folderName(dir);
356
519
  const where2 = `${tenant}/sources/${id2}`;
357
520
  const root = resolve(dir);
358
521
  const index = join4(root, "index.ts");
@@ -373,6 +536,8 @@ async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
373
536
  if (def?.kind !== "source") throw new SourceErrors(where2, ["index.ts must `export default defineSource({ \u2026 })`"]);
374
537
  const errors = [];
375
538
  if (def.id !== id2) errors.push(`the source's id "${def.id}" must match its folder, sources/${id2}`);
539
+ const buckets = normalizeSourcePace(def.pace, errors);
540
+ const hasDefaultBucket = Object.hasOwn(buckets, "default");
376
541
  const ops = {};
377
542
  for (const [name, op] of Object.entries(def.ops ?? {})) {
378
543
  if (!op?.input || typeof op.input !== "object" || !("~standard" in op.input))
@@ -380,7 +545,25 @@ async function compileSource(tenant, dir, tenantRoot = resolve(dir, "../..")) {
380
545
  if (typeof op?.call !== "function") errors.push(`op ${name}: call must be a function`);
381
546
  const ttl = ttlSeconds(op?.ttl);
382
547
  if (typeof ttl === "string") errors.push(`op ${name}: ${ttl}`);
383
- ops[name] = { ttlSeconds: typeof ttl === "number" ? ttl : 0 };
548
+ let opBuckets;
549
+ if (op?.pace === void 0) {
550
+ if (hasDefaultBucket) opBuckets = ["default"];
551
+ } else if (op.pace === false) {
552
+ opBuckets = void 0;
553
+ } else if (Array.isArray(op.pace)) {
554
+ if (!op.pace.length || op.pace.some((b) => typeof b !== "string")) errors.push(`op ${name}: pace list must be a non-empty array of bucket names`);
555
+ else opBuckets = [...op.pace];
556
+ } else if (typeof op.pace === "object" && op.pace !== null) {
557
+ const bucketKey = Object.hasOwn(buckets, name) ? `op_${name}` : name;
558
+ const spec = normalizeBucketSpec(`op ${name}`, op.pace, errors);
559
+ if (spec) {
560
+ buckets[bucketKey] = spec;
561
+ opBuckets = [bucketKey];
562
+ }
563
+ } else {
564
+ errors.push(`op ${name}: pace must be false, a list of bucket names, or { requests, per, concurrency }`);
565
+ }
566
+ ops[name] = { ttlSeconds: typeof ttl === "number" ? ttl : 0, ...opBuckets ? { buckets: opBuckets } : {} };
384
567
  }
385
568
  const out = await build(
386
569
  options(
@@ -400,6 +583,7 @@ export default serveSource(def);
400
583
  title: yaml.data?.title ?? def.title ?? id2,
401
584
  hosts: [...def.hosts ?? []],
402
585
  secrets: [...def.secrets ?? []],
586
+ ...Object.keys(buckets).length ? { buckets } : {},
403
587
  ops,
404
588
  bundle: sha256(bundle2)
405
589
  };
@@ -441,10 +625,14 @@ function writeSourceTypes(tenantDir, sources) {
441
625
  }
442
626
  function reportSources(sources) {
443
627
  for (const { manifest: m, bundle: bundle2 } of sources) {
628
+ const bucketSummary = m.buckets ? ` pace=[${Object.keys(m.buckets).join(", ")}]` : "";
444
629
  console.log(
445
- ` source ${m.source} @ ${m.sha.slice(0, 10)} ${(bundle2.length / 1024).toFixed(0)} KB, hosts=[${m.hosts.join(", ")}] secrets=[${m.secrets.join(", ")}]`
630
+ ` source ${m.source} @ ${m.sha.slice(0, 10)} ${(bundle2.length / 1024).toFixed(0)} KB, hosts=[${m.hosts.join(", ")}] secrets=[${m.secrets.join(", ")}]${bucketSummary}`
446
631
  );
447
- for (const [op, { ttlSeconds: ttlSeconds2 }] of Object.entries(m.ops)) console.log(` op ${m.source}.${op}${ttlSeconds2 ? ` ttl=${ttlSeconds2}s` : ""}`);
632
+ for (const [op, { ttlSeconds: ttlSeconds2, buckets }] of Object.entries(m.ops)) {
633
+ const pace = buckets?.length ? ` pace=[${buckets.join(", ")}]` : "";
634
+ console.log(` op ${m.source}.${op}${ttlSeconds2 ? ` ttl=${ttlSeconds2}s` : ""}${pace}`);
635
+ }
448
636
  }
449
637
  }
450
638
  async function publishSources(post, tenant, sources, opts) {
@@ -479,11 +667,15 @@ function monorepoTenants() {
479
667
  if (!existsSync4(dir)) return null;
480
668
  return readdirSync3(dir).filter((name) => !name.startsWith(".") && existsSync4(join5(dir, name, "tenant.yaml"))).sort().map((name) => join5(dir, name));
481
669
  }
670
+ function folderName(dir) {
671
+ const leaf = win32.basename(win32.normalize(dir));
672
+ return leaf !== "." && leaf !== ".." ? leaf : win32.basename(resolve2(dir));
673
+ }
482
674
  function tenantIdentity(dir) {
483
675
  const meta = readYaml(join5(dir, "tenant.yaml")) ?? {};
484
676
  const motionsDir = join5(dir, "motions");
485
677
  const motions = existsSync4(motionsDir) ? readdirSync3(motionsDir).filter((name) => existsSync4(join5(motionsDir, name, "motion.yaml"))).sort() : [];
486
- return { id: meta.id ?? basename(dir), motions };
678
+ return { id: meta.id ?? folderName(dir), motions };
487
679
  }
488
680
  var readYaml = (path) => YAML2.parse(readFileSync4(path, "utf8"));
489
681
  var grant = (g) => ({ read: g?.read ?? [], propose: g?.propose ?? [] });
@@ -510,7 +702,8 @@ var MotionErrors = class extends Error {
510
702
  async function compileMotion(tenant, dir) {
511
703
  const tenantDir = findTenantDir(dir);
512
704
  if (!tenantDir) throw new Error(`no tenant.yaml above ${dir}`);
513
- const where2 = `${tenant.id}/${dir.split("/").at(-1)}/motion.yaml`;
705
+ const folder = folderName(dir);
706
+ const where2 = `${tenant.id}/${folder}/motion.yaml`;
514
707
  const parsed2 = parseMotion(readYaml(join5(dir, "motion.yaml")));
515
708
  if (!parsed2.ok) throw new MotionErrors(where2, parsed2.errors);
516
709
  const raw = parsed2.motion;
@@ -549,10 +742,11 @@ async function compileMotion(tenant, dir) {
549
742
  for (const [id2, q] of Object.entries(raw.queues ?? {})) {
550
743
  queues[id2] = { title: q.title, owner: q.owner ?? approvers[0] ?? "operator", deadline: q.deadline, default: q.default ?? "hold" };
551
744
  }
745
+ const motion = raw.motion ?? folder;
552
746
  const manifest = {
553
747
  tenant: tenant.id,
554
- motion: raw.motion ?? dir.split("/").at(-1),
555
- title: raw.title ?? raw.motion ?? dir,
748
+ motion,
749
+ title: raw.title ?? motion,
556
750
  timezone: raw.timezone ?? tenant.timezone,
557
751
  calendar: raw.calendar ?? {},
558
752
  approvers,
@@ -579,7 +773,7 @@ function compileInput(input) {
579
773
  async function compileTenant(tenantDir) {
580
774
  const dir = resolve2(tenantDir);
581
775
  const meta = readYaml(join5(dir, "tenant.yaml")) ?? {};
582
- const id2 = meta.id ?? dir.split("/").filter(Boolean).at(-1);
776
+ const id2 = meta.id ?? folderName(tenantDir);
583
777
  const timezone = meta.timezone ?? "America/Sao_Paulo";
584
778
  const connection = readYaml(join5(dir, "crm.yaml"));
585
779
  const seedPath = join5(dir, "crm-seed.json");
@@ -601,7 +795,7 @@ function tenantCrmProblems(tenant, systems = CRM_WRITES) {
601
795
 
602
796
  // src/init.ts
603
797
  import { existsSync as existsSync5, mkdirSync as mkdirSync2, readdirSync as readdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
604
- import { basename as basename2, dirname as dirname4, join as join6, resolve as resolve3 } from "path";
798
+ import { basename, dirname as dirname4, join as join6, resolve as resolve3 } from "path";
605
799
  import { fileURLToPath as fileURLToPath3 } from "url";
606
800
  var TENANT_ID = /^[a-z][a-z0-9_-]{0,62}$/;
607
801
  function cliVersion() {
@@ -614,7 +808,7 @@ var file = (dir, path, contents) => {
614
808
  };
615
809
  function init(target = ".") {
616
810
  const dir = resolve3(target);
617
- const id2 = basename2(dir);
811
+ const id2 = basename(dir);
618
812
  if (!TENANT_ID.test(id2)) throw new Error(`${id2} is not a tenant id: lowercase letters, digits, - and _, starting with a letter`);
619
813
  if (existsSync5(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
620
814
  mkdirSync2(dir, { recursive: true });
@@ -818,13 +1012,78 @@ function inside(root, rel) {
818
1012
  return dest;
819
1013
  }
820
1014
 
1015
+ // src/vitest.ts
1016
+ import { spawnSync } from "child_process";
1017
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
1018
+ import { dirname as dirname5, join as join8, resolve as resolve5, sep as sep4 } from "path";
1019
+ function findVitestPackage(dir) {
1020
+ for (let at = resolve5(dir); ; ) {
1021
+ const candidate = join8(at, "node_modules", "vitest", "package.json");
1022
+ if (existsSync7(candidate)) return candidate;
1023
+ const parent = dirname5(at);
1024
+ if (parent === at) return null;
1025
+ at = parent;
1026
+ }
1027
+ }
1028
+ function resolveVitest(dir) {
1029
+ const pkgPath = findVitestPackage(dir);
1030
+ if (pkgPath) {
1031
+ try {
1032
+ const pkg = JSON.parse(readFileSync7(pkgPath, "utf8"));
1033
+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.vitest ?? "./vitest.mjs";
1034
+ const entry = resolve5(dirname5(pkgPath), rel);
1035
+ if (existsSync7(entry)) return entry;
1036
+ } catch {
1037
+ }
1038
+ }
1039
+ throw new Error(`${dir} has no vitest. Add it to devDependencies and install.`);
1040
+ }
1041
+ function vitestConfig(dir) {
1042
+ const root = resolve5(dir);
1043
+ const folder = join8(root, "node_modules", ".motions");
1044
+ mkdirSync3(folder, { recursive: true });
1045
+ const stub = join8(folder, "workers-stub.js");
1046
+ writeFileSync3(stub, "export class WorkerEntrypoint {}\n");
1047
+ const config = join8(folder, "vitest.config.ts");
1048
+ writeFileSync3(
1049
+ config,
1050
+ `import { defineConfig } from "vitest/config";
1051
+
1052
+ export default defineConfig({
1053
+ root: ${JSON.stringify(root.split(sep4).join("/"))},
1054
+ resolve: { alias: { "cloudflare:workers": ${JSON.stringify(stub.split(sep4).join("/"))} } },
1055
+ test: {
1056
+ include: ["motions/*/tests/**/*.test.ts"],
1057
+ passWithNoTests: true,
1058
+ server: { deps: { inline: [/@motionskit\\/sdk/, /@motionskit\\/kernel/] } },
1059
+ },
1060
+ });
1061
+ `
1062
+ );
1063
+ return config;
1064
+ }
1065
+ function runVitest(dir, spawn = spawnSync) {
1066
+ const entry = resolveVitest(dir);
1067
+ const run2 = spawn(process.execPath, [entry, "run", "--config", vitestConfig(dir)], { cwd: dir, stdio: "inherit" });
1068
+ if (run2.error) throw run2.error;
1069
+ return run2.status === 0;
1070
+ }
1071
+ function runTenantTests(dirs, spawn = spawnSync) {
1072
+ let failed = 0;
1073
+ for (const dir of dirs) {
1074
+ if (!runVitest(dir, spawn)) failed++;
1075
+ }
1076
+ if (failed) throw new Error(`${failed} tenant${failed > 1 ? "s" : ""} failed the tests`);
1077
+ }
1078
+
821
1079
  // src/main.ts
822
- var USAGE = `usage: motions <check|push|pull|test|open|init|publish> \u2026
1080
+ var USAGE = `usage: motions <check|push|pull|test|open|retry|init|publish> \u2026
823
1081
  check [tenant] compile the tenant in this directory, or every tenant in this repo
824
1082
  push [--live] [-m message] publish a draft (or go live with --live) and print a link
825
1083
  pull <version> [--motion id] [--force]
826
1084
  test run motions/*/tests with the tenant's vitest
827
- open <tenant> <motion> [--list name | --companies id,id] [--label text]
1085
+ open <tenant> <motion> [--list id-or-name | --companies id,id] [--label text] [--again]
1086
+ retry <batch> [--company id] [--step id]
828
1087
  init [dir] scaffold a tenant repo
829
1088
  publish [tenant] from this repo, push --live over tenants/*`;
830
1089
  var parsed = (() => {
@@ -841,6 +1100,9 @@ var parsed = (() => {
841
1100
  force: { type: "boolean", default: false },
842
1101
  list: { type: "string" },
843
1102
  companies: { type: "string" },
1103
+ company: { type: "string" },
1104
+ step: { type: "string" },
1105
+ again: { type: "boolean", default: false },
844
1106
  label: { type: "string" },
845
1107
  reseed: { type: "boolean", default: false },
846
1108
  help: { type: "boolean", short: "h", default: false }
@@ -862,14 +1124,14 @@ var [command, ...args] = positionals;
862
1124
  var url = values.url.replace(/\/$/, "");
863
1125
  function resolveTenants(positional, fallbackAll) {
864
1126
  if (values.tenant) {
865
- const found = findTenantDir(resolve5(values.tenant));
1127
+ const found = findTenantDir(resolve6(values.tenant));
866
1128
  if (!found) throw new Error(`no tenant.yaml in ${values.tenant}`);
867
1129
  return [found];
868
1130
  }
869
1131
  if (positional) {
870
- const direct = findTenantDir(resolve5(positional));
871
- if (existsSync7(positional) && direct) return [direct];
872
- const match = monorepoTenants()?.find((dir) => dir.split(sep4).at(-1) === positional);
1132
+ const direct = findTenantDir(resolve6(positional));
1133
+ if (existsSync8(positional) && direct) return [direct];
1134
+ const match = monorepoTenants()?.find((dir) => folderName(dir) === positional);
873
1135
  if (match) return [match];
874
1136
  throw new Error(`no tenant ${positional}`);
875
1137
  }
@@ -911,7 +1173,7 @@ async function check(only) {
911
1173
  for (const dir of resolveTenants(only, true)) {
912
1174
  const tenant = await compileTenant(dir).catch((e) => {
913
1175
  failed++;
914
- console.error(`${dir.split(sep4).at(-1)}: ${e.message}`);
1176
+ console.error(`${folderName(dir)}: ${e.message}`);
915
1177
  return null;
916
1178
  });
917
1179
  if (!tenant) continue;
@@ -945,7 +1207,7 @@ async function push() {
945
1207
  async function publish(only) {
946
1208
  const all = monorepoTenants();
947
1209
  if (!all) throw new Error("publish runs over this repo's tenants/*; from a tenant repo use motions push --live");
948
- const dirs = only ? all.filter((dir) => dir.split(sep4).at(-1) === only) : all;
1210
+ const dirs = only ? all.filter((dir) => folderName(dir) === only) : all;
949
1211
  if (only && !dirs.length) throw new Error(`no tenant ${only}`);
950
1212
  await pushDirs(dirs, !values.draft);
951
1213
  }
@@ -966,8 +1228,8 @@ async function pull(version) {
966
1228
  if (!motion) throw new Error(`this tenant has ${motions.length} motions; pass --motion <id>`);
967
1229
  const sha = await resolveSha(id2, motion, version);
968
1230
  const { files } = await api(url, `/api/tenants/${id2}/motions/${motion}/versions/${sha}/files`);
969
- const motionDir = join8(dir, "motions", motion);
970
- const writes = Object.entries(files).map(([path, next]) => ({ rel: join8("motions", motion, path), path, next }));
1231
+ const motionDir = join9(dir, "motions", motion);
1232
+ const writes = Object.entries(files).map(([path, next]) => ({ rel: join9("motions", motion, path), path, next }));
971
1233
  if (!values.force) {
972
1234
  const blocked = blockedOverwrites(dir, writes);
973
1235
  if (blocked.length) throw new Error(`refusing to overwrite uncommitted changes (pass --force):
@@ -978,11 +1240,11 @@ async function pull(version) {
978
1240
  let unchanged = 0;
979
1241
  for (const write of writes.sort((a, b) => a.rel < b.rel ? -1 : 1)) {
980
1242
  const dest = inside(motionDir, write.path);
981
- const existed = existsSync7(dest);
982
- const same = existed && readFileSync7(dest, "utf8") === write.next;
1243
+ const existed = existsSync8(dest);
1244
+ const same = existed && readFileSync8(dest, "utf8") === write.next;
983
1245
  if (!same) {
984
- mkdirSync3(dirname5(dest), { recursive: true });
985
- writeFileSync3(dest, write.next);
1246
+ mkdirSync4(dirname6(dest), { recursive: true });
1247
+ writeFileSync4(dest, write.next);
986
1248
  }
987
1249
  if (!existed) {
988
1250
  created++;
@@ -994,55 +1256,62 @@ async function pull(version) {
994
1256
  }
995
1257
  console.log(`pulled ${id2}/${motion} @ ${sha.slice(0, 10)} (${created} created, ${updated} updated, ${unchanged} unchanged)`);
996
1258
  }
997
- function vitestConfig(dir) {
998
- const folder = join8(dir, "node_modules", ".motions");
999
- mkdirSync3(folder, { recursive: true });
1000
- const stub = join8(folder, "workers-stub.js");
1001
- writeFileSync3(stub, "export class WorkerEntrypoint {}\n");
1002
- const config = join8(folder, "vitest.config.ts");
1003
- writeFileSync3(
1004
- config,
1005
- `import { defineConfig } from "vitest/config";
1006
-
1007
- export default defineConfig({
1008
- root: ${JSON.stringify(dir)},
1009
- resolve: { alias: { "cloudflare:workers": ${JSON.stringify(stub)} } },
1010
- test: {
1011
- include: ["motions/*/tests/**/*.test.ts"],
1012
- passWithNoTests: true,
1013
- server: { deps: { inline: [/@motionskit\\/sdk/, /@motionskit\\/kernel/] } },
1014
- },
1015
- });
1016
- `
1017
- );
1018
- return config;
1019
- }
1020
1259
  async function test(only) {
1021
- let failed = 0;
1022
- for (const dir of resolveTenants(only, true)) {
1023
- const bin = join8(dir, "node_modules", ".bin", "vitest");
1024
- if (!existsSync7(bin)) throw new Error(`${dir} has no vitest. Add it to devDependencies and install.`);
1025
- const run2 = spawnSync(bin, ["run", "--config", vitestConfig(dir)], { cwd: dir, stdio: "inherit" });
1026
- if (run2.status !== 0) failed++;
1260
+ runTenantTests(resolveTenants(only, true));
1261
+ }
1262
+ function optionalTenant() {
1263
+ if (values.tenant) {
1264
+ const found = findTenantDir(resolve6(values.tenant));
1265
+ return found ? tenantIdentity(found).id : values.tenant;
1027
1266
  }
1028
- if (failed) throw new Error(`${failed} tenant${failed > 1 ? "s" : ""} failed the tests`);
1267
+ const here = findTenantDir(process.cwd());
1268
+ return here ? tenantIdentity(here).id : void 0;
1029
1269
  }
1030
- async function open(tenant, motion) {
1031
- if (!tenant || !motion) throw new Error("usage: motions open <tenant> <motion> [--list name | --companies id,id] [--label text]");
1032
- const out = await api(url, `/api/tenants/${tenant}/motions/${motion}/batches`, {
1270
+ async function open(tenant, motion, extra) {
1271
+ if (!tenant || !motion || extra) {
1272
+ throw new Error("usage: motions open <tenant> <motion> [--list id-or-name | --companies id,id] [--label text] [--again]");
1273
+ }
1274
+ const out = await openBatch((path, body, t) => api(url, path, body, t), {
1275
+ tenant,
1276
+ motion,
1033
1277
  list: values.list,
1034
- companies: values.companies?.split(",").map((s) => s.trim()),
1035
- label: values.label
1278
+ companies: values.companies,
1279
+ label: values.label,
1280
+ again: values.again
1036
1281
  });
1037
- console.log(`opened batch ${out.id} with ${out.companies} companies`);
1282
+ const suffix = out.reused ? " (existing batch for this list and version; pass --again to open another)" : out.skipped ? ` (${out.skipped} skipped)` : out.missing?.length ? ` (${out.missing.length} not in CRM)` : "";
1283
+ console.log(`${out.reused ? "reused" : "opened"} batch ${out.id} with ${out.companies} companies${suffix}`);
1038
1284
  console.log(` ${url}/t/${tenant}/batches/${out.id}`);
1039
1285
  }
1286
+ async function retry(batch, extra) {
1287
+ if (!batch || extra || values.companies !== void 0) {
1288
+ throw new Error("usage: motions retry <batch> [--company id] [--step id]");
1289
+ }
1290
+ const { tenant, retried } = await retryBatch((path, body, t) => api(url, path, body, t), {
1291
+ batch,
1292
+ company: values.company,
1293
+ step: values.step,
1294
+ tenant: optionalTenant()
1295
+ });
1296
+ if (!retried.length) {
1297
+ console.log(values.step ? `nothing to retry at ${values.step} in ${batch}` : `nothing to retry in ${batch}`);
1298
+ return;
1299
+ }
1300
+ if (retried.length === 1) {
1301
+ console.log(`retried ${retried[0].company} at ${retried[0].step}`);
1302
+ } else {
1303
+ console.log(`retried ${retried.length} cells in ${batch}:`);
1304
+ for (const target of retried) console.log(` ${target.company} \xB7 ${target.step}`);
1305
+ }
1306
+ console.log(` ${url}/t/${tenant}/batches/${batch}`);
1307
+ }
1040
1308
  var commands = {
1041
1309
  check,
1042
1310
  push,
1043
1311
  pull,
1044
1312
  test,
1045
1313
  open,
1314
+ retry,
1046
1315
  init: (dir) => {
1047
1316
  const created = init(dir);
1048
1317
  console.log(`created ${created}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionskit/cli",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "esbuild": "^0.28.2",
30
30
  "yaml": "^2.9.1",
31
31
  "zod": "^4.6.7",
32
- "@motionskit/kernel": "0.2.0"
32
+ "@motionskit/kernel": "0.2.3"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^22.19.0",