@ductape/cli 0.4.2 → 0.4.4

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.
@@ -2,6 +2,8 @@ interface MigrateOpts {
2
2
  env?: string;
3
3
  db?: string;
4
4
  dryRun?: boolean;
5
+ to?: string;
6
+ json?: boolean;
5
7
  }
6
8
  interface MigrateStatusOpts {
7
9
  env?: string;
@@ -14,6 +16,7 @@ interface MigrateRollbackOpts {
14
16
  n?: number;
15
17
  }
16
18
  export declare function runDbMigrate(opts: MigrateOpts): Promise<void>;
19
+ export declare function runDbMigrateBaseline(opts: MigrateOpts): Promise<void>;
17
20
  export declare function runDbMigrateStatus(opts: MigrateStatusOpts): Promise<void>;
18
21
  export declare function runDbMigrateRollback(opts: MigrateRollbackOpts): Promise<void>;
19
22
  export {};
@@ -67,25 +67,38 @@ export async function runDbMigrate(opts) {
67
67
  const dbContext = buildDbContext(db, envSlug, productTag);
68
68
  const migrations = loadMigrationFiles(dir, db);
69
69
  if (migrations.length === 0) {
70
- console.log(`[${db}] No migration files found. Run \`ductape db schema generate\` first.`);
70
+ if (!opts.json)
71
+ console.log(`[${db}] No migration files found. Run \`ductape db schema generate\` first.`);
71
72
  continue;
72
73
  }
73
74
  const appliedTags = await getAppliedTags(proxy, dbContext);
74
- const pending = migrations.filter((m) => !appliedTags.includes(m.tag));
75
+ const targetIndex = opts.to ? migrations.findIndex(m => m.tag === opts.to) : migrations.length - 1;
76
+ if (targetIndex < 0)
77
+ fail(`Unknown migration target: ${opts.to}`);
78
+ const selected = migrations.slice(0, targetIndex + 1);
79
+ const pending = selected.filter((m) => !appliedTags.includes(m.tag));
80
+ // The SDK plans the whole chain, checks dependencies, and blocks replay into an existing database.
81
+ const plan = await proxy.execute('migration.run', [migrations, { dryRun: true, to: opts.to }], dbContext);
82
+ if (opts.dryRun) {
83
+ totalDry += pending.length;
84
+ if (opts.json)
85
+ printJson({ database: db, mutationState: 'not_attempted', plan }, true);
86
+ else
87
+ console.log(`[${db}] Dry run: ${pending.map(m => m.tag).join(', ')}`);
88
+ continue;
89
+ }
75
90
  if (pending.length === 0) {
76
- console.log(`[${db}] Already up to date.`);
91
+ if (!opts.json)
92
+ console.log(`[${db}] Already up to date.`);
77
93
  continue;
78
94
  }
79
- console.log(`[${db}] ${pending.length} pending migration(s).`);
95
+ if (!opts.json)
96
+ console.log(`[${db}] ${pending.length} pending migration(s).`);
80
97
  for (const migration of pending) {
81
- if (opts.dryRun) {
82
- console.log(` [dry-run] Would apply: ${migration.tag}`);
83
- totalDry++;
84
- continue;
85
- }
86
- process.stdout.write(` Applying ${migration.tag}... `);
98
+ if (!opts.json)
99
+ process.stdout.write(` Applying ${migration.tag}... `);
87
100
  try {
88
- const response = await proxy.execute('migration.run', [[migration]], dbContext);
101
+ const response = await proxy.execute('migration.run', [migrations, { to: migration.tag }], dbContext);
89
102
  const migrationResult = getMigrationResult(response, migration.tag);
90
103
  if (migrationResult && !migrationResult.success) {
91
104
  throw new Error(migrationResult.error ?? 'SDK reported an unsuccessful migration');
@@ -97,24 +110,42 @@ export async function runDbMigrate(opts) {
97
110
  if (!appliedAfterRun.includes(migration.tag)) {
98
111
  throw new Error('the operation returned without error, but the migration tag is absent from migration history');
99
112
  }
100
- console.log('done');
113
+ if (!opts.json)
114
+ console.log('done');
101
115
  totalApplied++;
102
116
  }
103
117
  catch (err) {
104
- console.log('unverified');
118
+ if (!opts.json)
119
+ console.log('unverified');
105
120
  fail(`Migration "${migration.tag}" could not be verified: ` +
106
121
  `${err instanceof Error ? err.message : String(err)}. ` +
107
122
  'Do not rerun it until the live schema and migration history have been inspected.');
108
123
  }
109
124
  }
110
125
  }
111
- if (opts.dryRun) {
126
+ if (opts.json) {
127
+ if (!opts.dryRun)
128
+ printJson({ mutationState: 'confirmed', applied: totalApplied }, true);
129
+ }
130
+ else if (opts.dryRun) {
112
131
  console.log(`\nDry run: ${totalDry} migration(s) would be applied.`);
113
132
  }
114
133
  else {
115
134
  console.log(`\nApplied ${totalApplied} migration(s).`);
116
135
  }
117
136
  }
137
+ export async function runDbMigrateBaseline(opts) {
138
+ const found = findProjectConfig();
139
+ if (!found)
140
+ fail('No linked project. Run ductape link.');
141
+ if (!opts.db || !opts.to)
142
+ fail('Baseline requires --db and --to.');
143
+ const session = requireSession();
144
+ const context = buildDbContext(opts.db, opts.env ?? session.project.env_slug, session.project.product_tag);
145
+ const migrations = loadMigrationFiles(found.dir, opts.db);
146
+ const result = await getDbProxy(session).execute('migration.baseline', [migrations, { to: opts.to, dryRun: Boolean(opts.dryRun) }], context);
147
+ printJson(result, true);
148
+ }
118
149
  export async function runDbMigrateStatus(opts) {
119
150
  const found = findProjectConfig();
120
151
  if (!found)
@@ -134,7 +165,7 @@ export async function runDbMigrateStatus(opts) {
134
165
  const appliedTags = await getAppliedTags(proxy, dbContext);
135
166
  const applied = migrations.filter((m) => appliedTags.includes(m.tag)).map((m) => m.tag);
136
167
  const pending = migrations.filter((m) => !appliedTags.includes(m.tag)).map((m) => m.tag);
137
- statusReport[db] = { applied, pending };
168
+ statusReport[db] = { applied, pending, mutationState: 'not_attempted' };
138
169
  if (!opts.json) {
139
170
  console.log(`\n[${db}]`);
140
171
  if (applied.length > 0) {
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import { runResourceCrud, runResourcesList, runEventTopicCrud, runNotificationMe
17
17
  import { runCloud, runCloudPreflight } from './commands/cloud.js';
18
18
  import { runDb, runDbActions, runDbContext } from './commands/db.js';
19
19
  import { runComponentActions } from './commands/component-actions.js';
20
- import { runDbMigrate, runDbMigrateStatus, runDbMigrateRollback } from './commands/db-migrate.js';
20
+ import { runDbMigrate, runDbMigrateStatus, runDbMigrateRollback, runDbMigrateBaseline } from './commands/db-migrate.js';
21
21
  import { runFeaturesSync, runFeaturesValidate } from './commands/features-sync.js';
22
22
  import { runSessionsValidate } from './commands/sessions-validate.js';
23
23
  import { runDbSchemaGenerate, runDbSchemaPush } from './commands/db-schema.js';
@@ -809,7 +809,17 @@ const dbMigrate = db
809
809
  .option('--env <tag>', 'Override environment slug')
810
810
  .option('--db <tag>', 'Limit to one db entry from schema.json')
811
811
  .option('--dry-run', 'Print what would run without applying')
812
- .action(wrap((opts) => runDbMigrate({ env: opts.env, db: opts.db, dryRun: Boolean(opts.dryRun) })));
812
+ .option('--to <tag>', 'Apply through this migration, including dependencies')
813
+ .option('--json', 'Structured result')
814
+ .action(wrap((opts) => runDbMigrate({ env: opts.env, db: opts.db, to: opts.to, json: Boolean(opts.json), dryRun: Boolean(opts.dryRun) })));
815
+ dbMigrate.command('baseline')
816
+ .description('Verify live MongoDB schema and adopt migration history without replaying it')
817
+ .requiredOption('--db <tag>')
818
+ .requiredOption('--to <tag>')
819
+ .option('--env <tag>')
820
+ .option('--dry-run')
821
+ .option('--json')
822
+ .action(wrap(runDbMigrateBaseline));
813
823
  dbMigrate
814
824
  .command('status')
815
825
  .description('Show applied vs pending migrations')
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { parse } from '@babel/parser';
4
+ import { recordedNativeCalls } from './recorded-native-calls.js';
4
5
  const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts', '.mjs', '.cjs']);
5
6
  const NATIVE_NODES = new Map([
6
7
  ['IfStatement', ['FEATURE_NATIVE_IF', 'Replace native if/else with ctx.branch(ctx.when.*, { then, else }).']],
@@ -137,6 +138,9 @@ export function validateFeatureProject(projectRoot) {
137
138
  return;
138
139
  }
139
140
  visit(handler, { tag, mode });
141
+ for (const call of recordedNativeCalls(handler)) {
142
+ add(file, call, tag, 'FEATURE_NATIVE_RECORDED_METHOD', 'Native method on a recorded value. Use ctx.substring/ctx.transform or a portable Function.');
143
+ }
140
144
  return;
141
145
  }
142
146
  }
@@ -283,9 +283,19 @@ export async function configureProductApp(ctx, productRef, appRef, updates) {
283
283
  const productTag = String(product.tag ?? (!/^[a-f\d]{24}$/i.test(productRef) ? productRef : ''));
284
284
  if (!productTag)
285
285
  throw new Error(`Could not resolve product tag for "${productRef}"`);
286
- // Product fetch responses may omit app links. Resolve through the canonical
287
- // connected-App inventory so every app returned by `products apps list` works here.
288
- const listedLinks = await listProductApps(ctx, productTag, true);
286
+ // Prefer the raw link records already on the fetched product document — these are the
287
+ // product's own App connections (access_tag, per-env credentials) and match exactly what
288
+ // `products apps list` displays via the same `row.apps` field (see listProductApps above).
289
+ // `listProductApps(ctx, productTag, true)` looks like the more "canonical" source but is NOT:
290
+ // for full=true it calls GET /integrations/v1/fetch-product-apps/:product_id, which resolves
291
+ // integration.apps[].app_tag against the App/marketplace catalogue (products.service.ts's
292
+ // fetchIntegration -> fetchIntegrationApps) and returns App *definition* objects, not the
293
+ // product's link records — those have no access_tag or per-env credentials at all, which is
294
+ // exactly why every identifier from `products apps list` failed to resolve here (DT-084).
295
+ // Only fall back to the normalized listProductApps() path (full=false, matching the proven-
296
+ // working `products apps list` path) when the product document itself omits `apps`.
297
+ const rawLinks = Array.isArray(product.apps) ? product.apps : undefined;
298
+ const listedLinks = rawLinks ?? (await listProductApps(ctx, productTag, false));
289
299
  const links = listedLinks.filter((item) => Boolean(item && typeof item === 'object'));
290
300
  const normalized = appRef.toLowerCase();
291
301
  const link = links.find((item) => String(item.access_tag ?? '').toLowerCase() === normalized
@@ -0,0 +1 @@
1
+ export declare function recordedNativeCalls(root: any): Set<any>;
@@ -0,0 +1,71 @@
1
+ export function recordedNativeCalls(root) {
2
+ const context = root.params?.[0]?.name || 'ctx';
3
+ const tainted = new Set();
4
+ const nodes = [];
5
+ const walk = (node) => {
6
+ if (!node || typeof node !== 'object')
7
+ return;
8
+ if (typeof node.type === 'string')
9
+ nodes.push(node);
10
+ for (const [key, value] of Object.entries(node)) {
11
+ if (['loc', 'extra', 'start', 'end'].includes(key))
12
+ continue;
13
+ if (Array.isArray(value))
14
+ value.forEach(walk);
15
+ else if (value && typeof value === 'object')
16
+ walk(value);
17
+ }
18
+ };
19
+ walk(root);
20
+ const bind = (pattern) => {
21
+ if (!pattern)
22
+ return;
23
+ if (pattern.type === 'Identifier')
24
+ tainted.add(pattern.name);
25
+ if (pattern.type === 'ObjectPattern')
26
+ pattern.properties.forEach((p) => bind(p.value || p.argument));
27
+ if (pattern.type === 'ArrayPattern')
28
+ pattern.elements.forEach(bind);
29
+ if (pattern.type === 'AssignmentPattern')
30
+ bind(pattern.left);
31
+ };
32
+ const derived = (node) => {
33
+ if (!node)
34
+ return false;
35
+ if (node.type === 'Identifier')
36
+ return tainted.has(node.name);
37
+ if (['AwaitExpression', 'TSAsExpression', 'TSNonNullExpression', 'TSTypeAssertion'].includes(node.type))
38
+ return derived(node.argument || node.expression);
39
+ if (['MemberExpression', 'OptionalMemberExpression'].includes(node.type)) {
40
+ return (node.object?.name === context && (node.property?.name || node.property?.value) === 'input') || derived(node.object);
41
+ }
42
+ if (['CallExpression', 'OptionalCallExpression'].includes(node.type)) {
43
+ if (node.callee?.object?.object?.name === context && node.callee?.object?.property?.name === 'functions' && node.callee?.property?.name === 'use')
44
+ return false;
45
+ let receiver = node.callee;
46
+ while (receiver?.object)
47
+ receiver = receiver.object;
48
+ return receiver?.name === context || derived(node.callee) || node.arguments.some(derived);
49
+ }
50
+ if (node.type === 'ObjectExpression')
51
+ return node.properties.some((p) => derived(p.value || p.argument));
52
+ if (node.type === 'ArrayExpression')
53
+ return node.elements.some(derived);
54
+ return false;
55
+ };
56
+ // Resolve aliases and destructuring to a fixed point, including aliases declared later.
57
+ for (let iteration = 0; iteration <= nodes.length; iteration++) {
58
+ const count = tainted.size;
59
+ for (const node of nodes) {
60
+ if (node.type === 'VariableDeclarator' && derived(node.init))
61
+ bind(node.id);
62
+ if (node.type === 'AssignmentExpression' && derived(node.right))
63
+ bind(node.left);
64
+ }
65
+ if (count === tainted.size)
66
+ break;
67
+ }
68
+ return new Set(nodes.filter(node => ['CallExpression', 'OptionalCallExpression'].includes(node.type) &&
69
+ ['MemberExpression', 'OptionalMemberExpression'].includes(node.callee?.type) &&
70
+ derived(node.callee.object) && node.callee.object?.name !== context));
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ductape/cli",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "description": "Ductape CLI — local platform, login, link projects, and manage resources via the proxy (Workbench-compatible)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",