@nicnocquee/dataqueue 1.32.0 → 1.33.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/cli.js CHANGED
@@ -1,23 +1,598 @@
1
1
  import { spawnSync } from 'child_process';
2
2
  import path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
+ import { readFileSync, existsSync, chmodSync, writeFileSync, mkdirSync } from 'fs';
5
+
6
+ // src/cli.ts
7
+ var DEPENDENCIES_TO_ADD = [
8
+ "@nicnocquee/dataqueue",
9
+ "@nicnocquee/dataqueue-dashboard",
10
+ "@nicnocquee/dataqueue-react"
11
+ ];
12
+ var DEV_DEPENDENCIES_TO_ADD = [
13
+ "dotenv-cli",
14
+ "ts-node",
15
+ "node-pg-migrate"
16
+ ];
17
+ var SCRIPTS_TO_ADD = {
18
+ cron: "bash cron.sh",
19
+ "migrate-dataqueue": "dotenv -e .env.local -- dataqueue-cli migrate"
20
+ };
21
+ var APP_ROUTER_ROUTE_TEMPLATE = `/**
22
+ * This end point is used to manage the job queue.
23
+ * It supports the following tasks:
24
+ * - reclaim: Reclaim stuck jobs
25
+ * - cleanup: Cleanup old jobs
26
+ * - process: Process jobs
27
+ *
28
+ * Example usage with default values (reclaim stuck jobs for 10 minutes, cleanup old jobs for 30 days, and process jobs with batch size 3, concurrency 2, and verbose true):
29
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/reclaim -H "Authorization: Bearer $CRON_SECRET"
30
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/cleanup -H "Authorization: Bearer $CRON_SECRET"
31
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/process -H "Authorization: Bearer $CRON_SECRET"
32
+ *
33
+ * Example usage with custom values:
34
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/reclaim -H "Authorization: Bearer $CRON_SECRET" -d '{"maxProcessingTimeMinutes": 15}' -H "Content-Type: application/json"
35
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/cleanup -H "Authorization: Bearer $CRON_SECRET" -d '{"daysToKeep": 15}' -H "Content-Type: application/json"
36
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/process -H "Authorization: Bearer $CRON_SECRET" -d '{"batchSize": 5, "concurrency": 3, "verbose": false, "workerId": "custom-worker-id"}' -H "Content-Type: application/json"
37
+ *
38
+ * During development, you can run the following script to run the cron jobs continuously in the background:
39
+ * pnpm cron
40
+ */
41
+ import { getJobQueue, jobHandlers } from '@/lib/dataqueue/queue';
42
+ import { NextResponse } from 'next/server';
43
+
44
+ export async function POST(
45
+ request: Request,
46
+ { params }: { params: Promise<{ task: string[] }> },
47
+ ) {
48
+ const { task } = await params;
49
+ const authHeader = request.headers.get('authorization');
50
+ if (authHeader !== \`Bearer \${process.env.CRON_SECRET}\`) {
51
+ return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
52
+ }
53
+
54
+ if (!task || task.length === 0) {
55
+ return NextResponse.json({ message: 'Task is required' }, { status: 400 });
56
+ }
57
+
58
+ const supportedTasks = ['reclaim', 'cleanup', 'process'];
59
+ const theTask = task[0];
60
+ if (!supportedTasks.includes(theTask)) {
61
+ return NextResponse.json(
62
+ { message: 'Task not supported' },
63
+ { status: 400 },
64
+ );
65
+ }
66
+
67
+ try {
68
+ const jobQueue = getJobQueue();
69
+
70
+ if (theTask === 'reclaim') {
71
+ let maxProcessingTimeMinutes = 10;
72
+ try {
73
+ const body = await request.json();
74
+ maxProcessingTimeMinutes = body.maxProcessingTimeMinutes || 10;
75
+ } catch {
76
+ // ignore parsing error and use default value
77
+ }
78
+ const reclaimed = await jobQueue.reclaimStuckJobs(
79
+ maxProcessingTimeMinutes,
80
+ );
81
+ console.log(\`Reclaimed \${reclaimed} stuck jobs\`);
82
+ return NextResponse.json({
83
+ message: \`Stuck jobs reclaimed: \${reclaimed} with maxProcessingTimeMinutes: \${maxProcessingTimeMinutes}\`,
84
+ reclaimed,
85
+ });
86
+ }
87
+
88
+ if (theTask === 'cleanup') {
89
+ let daysToKeep = 30;
90
+ try {
91
+ const body = await request.json();
92
+ daysToKeep = body.daysToKeep || 30;
93
+ } catch {
94
+ // ignore parsing error and use default value
95
+ }
96
+ const deleted = await jobQueue.cleanupOldJobs(daysToKeep);
97
+ console.log(\`Deleted \${deleted} old jobs\`);
98
+ return NextResponse.json({
99
+ message: \`Old jobs cleaned up: \${deleted} with daysToKeep: \${daysToKeep}\`,
100
+ deleted,
101
+ });
102
+ }
103
+
104
+ if (theTask === 'process') {
105
+ let batchSize = 3;
106
+ let concurrency = 2;
107
+ let verbose = true;
108
+ let workerId = \`manage-\${theTask}-\${Date.now()}\`;
109
+ try {
110
+ const body = await request.json();
111
+ batchSize = body.batchSize || 3;
112
+ concurrency = body.concurrency || 2;
113
+ verbose = body.verbose || true;
114
+ workerId = body.workerId || \`manage-\${theTask}-\${Date.now()}\`;
115
+ } catch {
116
+ // ignore parsing error and use default value
117
+ }
118
+ const processor = jobQueue.createProcessor(jobHandlers, {
119
+ workerId,
120
+ batchSize,
121
+ concurrency,
122
+ verbose,
123
+ });
124
+ const processed = await processor.start();
125
+
126
+ return NextResponse.json({
127
+ message: \`Jobs processed: \${processed} with workerId: \${workerId}, batchSize: \${batchSize}, concurrency: \${concurrency}, and verbose: \${verbose}\`,
128
+ processed,
129
+ });
130
+ }
131
+
132
+ return NextResponse.json(
133
+ { message: 'Task not supported' },
134
+ { status: 400 },
135
+ );
136
+ } catch (error) {
137
+ console.error('Error processing jobs:', error);
138
+ return NextResponse.json(
139
+ { message: 'Failed to process jobs' },
140
+ { status: 500 },
141
+ );
142
+ }
143
+ }
144
+ `;
145
+ var PAGES_ROUTER_ROUTE_TEMPLATE = `/**
146
+ * This end point is used to manage the job queue.
147
+ * It supports the following tasks:
148
+ * - reclaim: Reclaim stuck jobs
149
+ * - cleanup: Cleanup old jobs
150
+ * - process: Process jobs
151
+ *
152
+ * Example usage with default values (reclaim stuck jobs for 10 minutes, cleanup old jobs for 30 days, and process jobs with batch size 3, concurrency 2, and verbose true):
153
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/reclaim -H "Authorization: Bearer $CRON_SECRET"
154
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/cleanup -H "Authorization: Bearer $CRON_SECRET"
155
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/process -H "Authorization: Bearer $CRON_SECRET"
156
+ *
157
+ * Example usage with custom values:
158
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/reclaim -H "Authorization: Bearer $CRON_SECRET" -d '{"maxProcessingTimeMinutes": 15}' -H "Content-Type: application/json"
159
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/cleanup -H "Authorization: Bearer $CRON_SECRET" -d '{"daysToKeep": 15}' -H "Content-Type: application/json"
160
+ * curl -X POST http://localhost:3000/api/dataqueue/manage/process -H "Authorization: Bearer $CRON_SECRET" -d '{"batchSize": 5, "concurrency": 3, "verbose": false, "workerId": "custom-worker-id"}' -H "Content-Type: application/json"
161
+ *
162
+ * During development, you can run the following script to run the cron jobs continuously in the background:
163
+ * pnpm cron
164
+ */
165
+ import type { NextApiRequest, NextApiResponse } from 'next';
166
+ import { getJobQueue, jobHandlers } from '@/lib/dataqueue/queue';
167
+
168
+ type ResponseBody = {
169
+ message: string;
170
+ reclaimed?: number;
171
+ deleted?: number;
172
+ processed?: number;
173
+ };
174
+
175
+ export default async function handler(
176
+ req: NextApiRequest,
177
+ res: NextApiResponse<ResponseBody>,
178
+ ) {
179
+ if (req.method !== 'POST') {
180
+ res.setHeader('Allow', 'POST');
181
+ return res.status(405).json({ message: 'Method not allowed' });
182
+ }
183
+
184
+ const authHeader = req.headers.authorization;
185
+ if (authHeader !== \`Bearer \${process.env.CRON_SECRET}\`) {
186
+ return res.status(401).json({ message: 'Unauthorized' });
187
+ }
188
+
189
+ const task = req.query.task;
190
+ const taskArray = Array.isArray(task) ? task : task ? [task] : [];
191
+ if (!taskArray.length) {
192
+ return res.status(400).json({ message: 'Task is required' });
193
+ }
194
+
195
+ const supportedTasks = ['reclaim', 'cleanup', 'process'];
196
+ const theTask = taskArray[0];
197
+ if (!supportedTasks.includes(theTask)) {
198
+ return res.status(400).json({ message: 'Task not supported' });
199
+ }
200
+
201
+ try {
202
+ const jobQueue = getJobQueue();
203
+ const body = typeof req.body === 'object' && req.body ? req.body : {};
204
+
205
+ if (theTask === 'reclaim') {
206
+ const maxProcessingTimeMinutes = body.maxProcessingTimeMinutes || 10;
207
+ const reclaimed = await jobQueue.reclaimStuckJobs(maxProcessingTimeMinutes);
208
+ console.log(\`Reclaimed \${reclaimed} stuck jobs\`);
209
+ return res.status(200).json({
210
+ message: \`Stuck jobs reclaimed: \${reclaimed} with maxProcessingTimeMinutes: \${maxProcessingTimeMinutes}\`,
211
+ reclaimed,
212
+ });
213
+ }
214
+
215
+ if (theTask === 'cleanup') {
216
+ const daysToKeep = body.daysToKeep || 30;
217
+ const deleted = await jobQueue.cleanupOldJobs(daysToKeep);
218
+ console.log(\`Deleted \${deleted} old jobs\`);
219
+ return res.status(200).json({
220
+ message: \`Old jobs cleaned up: \${deleted} with daysToKeep: \${daysToKeep}\`,
221
+ deleted,
222
+ });
223
+ }
224
+
225
+ const batchSize = body.batchSize || 3;
226
+ const concurrency = body.concurrency || 2;
227
+ const verbose = body.verbose || true;
228
+ const workerId = body.workerId || \`manage-\${theTask}-\${Date.now()}\`;
229
+ const processor = jobQueue.createProcessor(jobHandlers, {
230
+ workerId,
231
+ batchSize,
232
+ concurrency,
233
+ verbose,
234
+ });
235
+ const processed = await processor.start();
236
+
237
+ return res.status(200).json({
238
+ message: \`Jobs processed: \${processed} with workerId: \${workerId}, batchSize: \${batchSize}, concurrency: \${concurrency}, and verbose: \${verbose}\`,
239
+ processed,
240
+ });
241
+ } catch (error) {
242
+ console.error('Error processing jobs:', error);
243
+ return res.status(500).json({ message: 'Failed to process jobs' });
244
+ }
245
+ }
246
+ `;
247
+ var CRON_SH_TEMPLATE = `#!/bin/bash
248
+
249
+ # This script is used to run the cron jobs for the demo app during development.
250
+ # Run it with \`pnpm cron\` from the apps/demo directory.
251
+
252
+ set -a
253
+ source "$(dirname "$0")/.env.local"
254
+ set +a
255
+
256
+ if [ -z "$CRON_SECRET" ]; then
257
+ echo "Error: CRON_SECRET environment variable is not set in .env.local"
258
+ exit 1
259
+ fi
260
+
261
+ cleanup() {
262
+ kill 0
263
+ wait
264
+ }
265
+ trap cleanup SIGINT SIGTERM
266
+
267
+ while true; do
268
+ echo "Processing jobs..."
269
+ curl http://localhost:3000/api/dataqueue/manage/process -X POST -H "Authorization: Bearer $CRON_SECRET"
270
+ echo ""
271
+ sleep 10 # Process jobs every 10 seconds
272
+ done &
273
+
274
+ while true; do
275
+ echo "Reclaiming stuck jobs..."
276
+ curl http://localhost:3000/api/dataqueue/manage/reclaim -X POST -H "Authorization: Bearer $CRON_SECRET"
277
+ echo ""
278
+ sleep 20 # Reclaim stuck jobs every 20 seconds
279
+ done &
280
+
281
+ while true; do
282
+ echo "Cleaning up old jobs..."
283
+ curl http://localhost:3000/api/dataqueue/manage/cleanup -X POST -H "Authorization: Bearer $CRON_SECRET"
284
+ echo ""
285
+ sleep 30 # Cleanup old jobs every 30 seconds
286
+ done &
287
+
288
+ wait
289
+ `;
290
+ var QUEUE_TEMPLATE = `import { initJobQueue, JobHandlers } from '@nicnocquee/dataqueue';
291
+
292
+ export type JobPayloadMap = {
293
+ send_email: {
294
+ to: string;
295
+ subject: string;
296
+ body: string;
297
+ };
298
+ };
299
+
300
+ let jobQueue: ReturnType<typeof initJobQueue<JobPayloadMap>> | null = null;
301
+
302
+ export const getJobQueue = () => {
303
+ if (!jobQueue) {
304
+ jobQueue = initJobQueue<JobPayloadMap>({
305
+ databaseConfig: {
306
+ connectionString: process.env.PG_DATAQUEUE_DATABASE,
307
+ },
308
+ verbose: process.env.NODE_ENV === 'development',
309
+ });
310
+ }
311
+ return jobQueue;
312
+ };
313
+
314
+ export const jobHandlers: JobHandlers<JobPayloadMap> = {
315
+ send_email: async (payload) => {
316
+ const { to, subject, body } = payload;
317
+ console.log('send_email placeholder:', { to, subject, body });
318
+ },
319
+ };
320
+ `;
321
+ function runInit({
322
+ log = console.log,
323
+ error = console.error,
324
+ exit = (code) => process.exit(code),
325
+ cwd = process.cwd(),
326
+ readFileSyncImpl = readFileSync,
327
+ writeFileSyncImpl = writeFileSync,
328
+ existsSyncImpl = existsSync,
329
+ mkdirSyncImpl = mkdirSync,
330
+ chmodSyncImpl = chmodSync
331
+ } = {}) {
332
+ try {
333
+ log(`dataqueue: Initializing in ${cwd}...`);
334
+ log("");
335
+ const details = detectNextJsAndRouter({
336
+ cwd,
337
+ existsSyncImpl,
338
+ readFileSyncImpl
339
+ });
340
+ createScaffoldFiles({
341
+ details,
342
+ log,
343
+ existsSyncImpl,
344
+ mkdirSyncImpl,
345
+ writeFileSyncImpl,
346
+ chmodSyncImpl
347
+ });
348
+ updatePackageJson({
349
+ details,
350
+ log,
351
+ writeFileSyncImpl
352
+ });
353
+ log("");
354
+ log(
355
+ "Done! Run your package manager's install command to install new dependencies."
356
+ );
357
+ exit(0);
358
+ } catch (cause) {
359
+ const message = cause instanceof Error ? cause.message : String(cause);
360
+ error(`dataqueue: ${message}`);
361
+ exit(1);
362
+ }
363
+ }
364
+ function detectNextJsAndRouter({
365
+ cwd,
366
+ existsSyncImpl,
367
+ readFileSyncImpl
368
+ }) {
369
+ const packageJsonPath = path.join(cwd, "package.json");
370
+ if (!existsSyncImpl(packageJsonPath)) {
371
+ throw new Error("package.json not found in current directory.");
372
+ }
373
+ const packageJson = parsePackageJson(
374
+ readFileSyncImpl(packageJsonPath, "utf8"),
375
+ packageJsonPath
376
+ );
377
+ if (!isNextJsProject(packageJson)) {
378
+ throw new Error(
379
+ "Not a Next.js project. Could not find 'next' in package.json dependencies."
380
+ );
381
+ }
382
+ const srcDir = path.join(cwd, "src");
383
+ const srcRoot = existsSyncImpl(srcDir) ? "src" : ".";
384
+ const appDir = path.join(cwd, srcRoot, "app");
385
+ const pagesDir = path.join(cwd, srcRoot, "pages");
386
+ const hasAppDir = existsSyncImpl(appDir);
387
+ const hasPagesDir = existsSyncImpl(pagesDir);
388
+ if (!hasAppDir && !hasPagesDir) {
389
+ throw new Error(
390
+ "Could not detect Next.js router. Expected either app/ or pages/ directory."
391
+ );
392
+ }
393
+ const router = hasAppDir ? "app" : "pages";
394
+ return { cwd, packageJsonPath, packageJson, srcRoot, router };
395
+ }
396
+ function updatePackageJson({
397
+ details,
398
+ log,
399
+ writeFileSyncImpl
400
+ }) {
401
+ const packageJson = details.packageJson;
402
+ const dependencies = ensureStringMapSection(packageJson, "dependencies");
403
+ const devDependencies = ensureStringMapSection(
404
+ packageJson,
405
+ "devDependencies"
406
+ );
407
+ const scripts = ensureStringMapSection(packageJson, "scripts");
408
+ for (const dependency of DEPENDENCIES_TO_ADD) {
409
+ if (dependencies[dependency]) {
410
+ log(` [skipped] dependency ${dependency} (already exists)`);
411
+ continue;
412
+ }
413
+ dependencies[dependency] = "latest";
414
+ log(` [added] dependency ${dependency}`);
415
+ }
416
+ for (const devDependency of DEV_DEPENDENCIES_TO_ADD) {
417
+ if (devDependencies[devDependency]) {
418
+ log(` [skipped] devDependency ${devDependency} (already exists)`);
419
+ continue;
420
+ }
421
+ devDependencies[devDependency] = "latest";
422
+ log(` [added] devDependency ${devDependency}`);
423
+ }
424
+ for (const [scriptName, scriptValue] of Object.entries(SCRIPTS_TO_ADD)) {
425
+ if (scripts[scriptName]) {
426
+ log(` [skipped] script "${scriptName}" (already exists)`);
427
+ continue;
428
+ }
429
+ scripts[scriptName] = scriptValue;
430
+ log(` [added] script "${scriptName}"`);
431
+ }
432
+ writeFileSyncImpl(
433
+ details.packageJsonPath,
434
+ `${JSON.stringify(packageJson, null, 2)}
435
+ `
436
+ );
437
+ }
438
+ function createScaffoldFiles({
439
+ details,
440
+ log,
441
+ existsSyncImpl,
442
+ mkdirSyncImpl,
443
+ writeFileSyncImpl,
444
+ chmodSyncImpl
445
+ }) {
446
+ const appRoutePath = path.join(
447
+ details.cwd,
448
+ details.srcRoot,
449
+ "app",
450
+ "api",
451
+ "dataqueue",
452
+ "manage",
453
+ "[[...task]]",
454
+ "route.ts"
455
+ );
456
+ const pagesRoutePath = path.join(
457
+ details.cwd,
458
+ details.srcRoot,
459
+ "pages",
460
+ "api",
461
+ "dataqueue",
462
+ "manage",
463
+ "[[...task]].ts"
464
+ );
465
+ const queuePath = path.join(
466
+ details.cwd,
467
+ details.srcRoot,
468
+ "lib",
469
+ "dataqueue",
470
+ "queue.ts"
471
+ );
472
+ const cronPath = path.join(details.cwd, "cron.sh");
473
+ if (details.router === "app") {
474
+ createFileIfMissing({
475
+ absolutePath: appRoutePath,
476
+ content: APP_ROUTER_ROUTE_TEMPLATE,
477
+ existsSyncImpl,
478
+ mkdirSyncImpl,
479
+ writeFileSyncImpl,
480
+ log,
481
+ logPath: toRelativePath(details.cwd, appRoutePath)
482
+ });
483
+ log(
484
+ " [skipped] pages/api/dataqueue/manage/[[...task]].ts (router not selected)"
485
+ );
486
+ } else {
487
+ log(
488
+ " [skipped] app/api/dataqueue/manage/[[...task]]/route.ts (router not selected)"
489
+ );
490
+ createFileIfMissing({
491
+ absolutePath: pagesRoutePath,
492
+ content: PAGES_ROUTER_ROUTE_TEMPLATE,
493
+ existsSyncImpl,
494
+ mkdirSyncImpl,
495
+ writeFileSyncImpl,
496
+ log,
497
+ logPath: toRelativePath(details.cwd, pagesRoutePath)
498
+ });
499
+ }
500
+ createFileIfMissing({
501
+ absolutePath: cronPath,
502
+ content: CRON_SH_TEMPLATE,
503
+ existsSyncImpl,
504
+ mkdirSyncImpl,
505
+ writeFileSyncImpl,
506
+ log,
507
+ logPath: "cron.sh"
508
+ });
509
+ if (existsSyncImpl(cronPath)) {
510
+ chmodSyncImpl(cronPath, 493);
511
+ }
512
+ createFileIfMissing({
513
+ absolutePath: queuePath,
514
+ content: QUEUE_TEMPLATE,
515
+ existsSyncImpl,
516
+ mkdirSyncImpl,
517
+ writeFileSyncImpl,
518
+ log,
519
+ logPath: toRelativePath(details.cwd, queuePath)
520
+ });
521
+ }
522
+ function createFileIfMissing({
523
+ absolutePath,
524
+ content,
525
+ existsSyncImpl,
526
+ mkdirSyncImpl,
527
+ writeFileSyncImpl,
528
+ log,
529
+ logPath
530
+ }) {
531
+ if (existsSyncImpl(absolutePath)) {
532
+ log(` [skipped] ${logPath} (already exists)`);
533
+ return;
534
+ }
535
+ mkdirSyncImpl(path.dirname(absolutePath), { recursive: true });
536
+ writeFileSyncImpl(absolutePath, content);
537
+ log(` [created] ${logPath}`);
538
+ }
539
+ function parsePackageJson(content, filePath) {
540
+ try {
541
+ const parsed = JSON.parse(content);
542
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
543
+ throw new Error("package.json must contain an object.");
544
+ }
545
+ return parsed;
546
+ } catch (cause) {
547
+ throw new Error(
548
+ `Failed to parse package.json at ${filePath}: ${cause instanceof Error ? cause.message : String(cause)}`
549
+ );
550
+ }
551
+ }
552
+ function isNextJsProject(packageJson) {
553
+ const dependencies = packageJson.dependencies;
554
+ const devDependencies = packageJson.devDependencies;
555
+ return hasPackage(dependencies, "next") || hasPackage(devDependencies, "next");
556
+ }
557
+ function hasPackage(section, packageName) {
558
+ if (!section || typeof section !== "object" || Array.isArray(section)) {
559
+ return false;
560
+ }
561
+ return Boolean(section[packageName]);
562
+ }
563
+ function ensureStringMapSection(packageJson, sectionName) {
564
+ const currentValue = packageJson[sectionName];
565
+ if (!currentValue || typeof currentValue !== "object" || Array.isArray(currentValue)) {
566
+ packageJson[sectionName] = {};
567
+ }
568
+ return packageJson[sectionName];
569
+ }
570
+ function toRelativePath(cwd, absolutePath) {
571
+ const relative = path.relative(cwd, absolutePath);
572
+ return relative || ".";
573
+ }
4
574
 
5
575
  // src/cli.ts
6
576
  var __filename = fileURLToPath(import.meta.url);
7
577
  var __dirname = path.dirname(__filename);
8
578
  function runCli(argv, {
9
579
  log = console.log,
580
+ error = console.error,
10
581
  exit = (code) => process.exit(code),
11
582
  spawnSyncImpl = spawnSync,
12
- migrationsDir = path.join(__dirname, "../migrations")
583
+ migrationsDir = path.join(__dirname, "../migrations"),
584
+ initDeps,
585
+ runInitImpl = runInit
13
586
  } = {}) {
14
587
  const [, , command, ...restArgs] = argv;
15
588
  function printUsage() {
589
+ log("Usage:");
16
590
  log(
17
- "Usage: dataqueue-cli migrate [--envPath <path>] [-s <schema> | --schema <schema>]"
591
+ " dataqueue-cli migrate [--envPath <path>] [-s <schema> | --schema <schema>]"
18
592
  );
593
+ log(" dataqueue-cli init");
19
594
  log("");
20
- log("Options:");
595
+ log("Options for migrate:");
21
596
  log(
22
597
  " --envPath <path> Path to a .env file to load environment variables (passed to node-pg-migrate)"
23
598
  );
@@ -35,6 +610,14 @@ function runCli(argv, {
35
610
  log(
36
611
  " Example: PGSSLMODE=require NODE_EXTRA_CA_CERTS=/absolute/path/to/ca.crt PG_DATAQUEUE_DATABASE=... npx dataqueue-cli migrate"
37
612
  );
613
+ log("");
614
+ log("Notes for init:");
615
+ log(
616
+ " - Supports both Next.js App Router and Pages Router (prefers App Router if both exist)."
617
+ );
618
+ log(
619
+ " - Scaffolds endpoint, cron.sh, queue placeholder, and package.json entries."
620
+ );
38
621
  exit(1);
39
622
  }
40
623
  if (command === "migrate") {
@@ -71,6 +654,13 @@ function runCli(argv, {
71
654
  { stdio: "inherit" }
72
655
  );
73
656
  exit(result.status ?? 1);
657
+ } else if (command === "init") {
658
+ runInitImpl({
659
+ log,
660
+ error,
661
+ exit,
662
+ ...initDeps
663
+ });
74
664
  } else {
75
665
  printUsage();
76
666
  }