@base44-preview/cli 0.2.2-pr.677.e0cc2a5 → 0.2.2-pr.679.27ae567

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/index.js CHANGED
@@ -228838,7 +228838,7 @@ function normalizeBase44Env() {
228838
228838
  loadProjectEnvFiles();
228839
228839
 
228840
228840
  // src/cli/index.ts
228841
- import { dirname as dirname30, join as join41 } from "node:path";
228841
+ import { dirname as dirname31, join as join42 } from "node:path";
228842
228842
  import { fileURLToPath as fileURLToPath7 } from "node:url";
228843
228843
 
228844
228844
  // ../../node_modules/@clack/core/dist/index.mjs
@@ -230795,7 +230795,8 @@ var TestOverridesSchema = object({
230795
230795
  id: string2(),
230796
230796
  projectRoot: string2()
230797
230797
  }).optional(),
230798
- latestVersion: string2().nullable().optional()
230798
+ latestVersion: string2().nullable().optional(),
230799
+ claudeBin: string2().optional()
230799
230800
  });
230800
230801
 
230801
230802
  // src/core/config.ts
@@ -246851,6 +246852,17 @@ var GIT_HASH_PATTERN = /^[a-fA-F0-9]{7,64}$/;
246851
246852
  function isGitCommitHash(value) {
246852
246853
  return GIT_HASH_PATTERN.test(value);
246853
246854
  }
246855
+ async function hasUnpushedWork(cwd) {
246856
+ const status = await execa("git", ["status", "--porcelain", "--branch"], {
246857
+ cwd,
246858
+ reject: false
246859
+ });
246860
+ if (status.exitCode !== 0)
246861
+ return false;
246862
+ const [branch = "", ...changes] = status.stdout.split(`
246863
+ `).filter(Boolean);
246864
+ return changes.length > 0 || !branch.includes("...") || branch.includes("[ahead");
246865
+ }
246854
246866
 
246855
246867
  // src/core/site/git-hash.ts
246856
246868
  function workerBuildNeedsGitHashError() {
@@ -255336,6 +255348,7 @@ var deno2 = Object.freeze({
255336
255348
  });
255337
255349
  globalThis.Deno = deno2;
255338
255350
  globalThis.Buffer = Buffer2;
255351
+ if (typeof process !== "undefined") process.version = "v22.23.4";
255339
255352
  try {
255340
255353
  new AsyncLocalStorage().enterWith(void 0);
255341
255354
  } catch {
@@ -258307,7 +258320,7 @@ var TELEMETRY_PATCH = [
258307
258320
  var TELEMETRY_STORE_FIELDS = "reqId: crypto.randomUUID(), respondedAt: null, inflight: new Map(), inflightTotal: 0, hadRejection: false, hadNonOk: false, logBudget: 5";
258308
258321
 
258309
258322
  // ../functions-compiler/src/version.ts
258310
- var COMPILER_VERSION = "0.1.8";
258323
+ var COMPILER_VERSION = "0.1.9";
258311
258324
 
258312
258325
  // ../functions-compiler/src/worker-entry.ts
258313
258326
  function denoShimSource() {
@@ -262851,30 +262864,25 @@ var pipelineType = ZodPipeline.create;
262851
262864
  var fileMapSchema = recordType(stringType().min(1), stringType()).refine((files) => Object.keys(files).length > 0, {
262852
262865
  message: "must contain at least one file"
262853
262866
  });
262854
- var entryPathSchema = stringType().min(1).max(200);
262855
262867
  var bundleRequestSchema = objectType({
262856
262868
  entry: stringType().min(1),
262857
262869
  files: fileMapSchema,
262858
- entryPath: entryPathSchema.optional(),
262859
262870
  postResponseTelemetry: booleanType().optional(),
262860
- runtimeSecrets: booleanType().optional(),
262861
- sourceMap: booleanType().optional()
262871
+ runtimeSecrets: booleanType().optional()
262862
262872
  }).refine((body) => (body.entry in body.files), {
262863
262873
  message: "`entry` must be a key in `files`"
262864
262874
  });
262865
262875
  var appFunctionSchema = objectType({
262866
262876
  name: stringType().min(1),
262867
262877
  entry: stringType().min(1),
262868
- files: fileMapSchema,
262869
- entryPath: entryPathSchema.optional()
262878
+ files: fileMapSchema
262870
262879
  }).refine((fn) => (fn.entry in fn.files), {
262871
262880
  message: "`entry` must be a key in `files`"
262872
262881
  });
262873
262882
  var bundleAppRequestSchema = objectType({
262874
262883
  functions: arrayType(appFunctionSchema).min(1),
262875
262884
  postResponseTelemetry: booleanType().optional(),
262876
- runtimeSecrets: booleanType().optional(),
262877
- sourceMap: booleanType().optional()
262885
+ runtimeSecrets: booleanType().optional()
262878
262886
  }).refine((body) => new Set(body.functions.map((fn) => fn.name)).size === body.functions.length, { message: "function names must be unique" });
262879
262887
  var ACTIVATION_MODE = "pull";
262880
262888
 
@@ -263439,8 +263447,7 @@ function wsNativeVirtualPlugin() {
263439
263447
  }
263440
263448
 
263441
263449
  // ../functions-compiler/src/deno-bundle.ts
263442
- var MAIN_MODULE = "_bundled.mjs";
263443
- async function bundleToModule(prepared, nodeModulesDir = "none", sourceMap = false) {
263450
+ async function bundleToModule(prepared, nodeModulesDir = "none") {
263444
263451
  const dir = await mkdtemp(path21.join(tmpdir2(), "b44-bundle-"));
263445
263452
  try {
263446
263453
  await writeFile2(path21.join(dir, "deno.json"), JSON.stringify({ nodeModulesDir }));
@@ -263459,7 +263466,7 @@ async function bundleToModule(prepared, nodeModulesDir = "none", sourceMap = fal
263459
263466
  define: { __dirname: '"/"', __filename: '"/index.js"' },
263460
263467
  minify: true,
263461
263468
  ...prepared.banner ? { banner: { js: prepared.banner } } : {},
263462
- ...sourceMap ? { sourcemap: "linked", sourcesContent: false, outfile: MAIN_MODULE } : { sourcemap: false },
263469
+ sourcemap: false,
263463
263470
  logLevel: "silent",
263464
263471
  plugins: [
263465
263472
  wsNativeVirtualPlugin(),
@@ -263478,19 +263485,14 @@ async function bundleToModule(prepared, nodeModulesDir = "none", sourceMap = fal
263478
263485
  throw e;
263479
263486
  }
263480
263487
  const outputs = result.outputFiles ?? [];
263481
- const warnings = result.warnings.map((w) => w.text);
263482
- if (!sourceMap) {
263483
- if (outputs.length !== 1) {
263484
- throw new Error(`expected single-module output, got ${outputs.length} file(s)`);
263485
- }
263486
- return { ok: true, module: outputs[0].text, warnings };
263487
- }
263488
- const module = outputs.find((o) => o.path.endsWith(".mjs"));
263489
- const map = outputs.find((o) => o.path.endsWith(".map"));
263490
- if (outputs.length !== 2 || !module || !map) {
263491
- throw new Error(`expected a module and its source map, got ${outputs.map((o) => path21.basename(o.path)).join(", ") || "no files"}`);
263488
+ if (outputs.length !== 1) {
263489
+ throw new Error(`expected single-module output, got ${outputs.length} file(s)`);
263492
263490
  }
263493
- return { ok: true, module: module.text, map: map.text, warnings };
263491
+ return {
263492
+ ok: true,
263493
+ module: outputs[0].text,
263494
+ warnings: result.warnings.map((w) => w.text)
263495
+ };
263494
263496
  } finally {
263495
263497
  await rm2(dir, { recursive: true, force: true });
263496
263498
  }
@@ -263536,36 +263538,6 @@ function relativizeFile(file, dir) {
263536
263538
  return file.startsWith(prefix) ? file.slice(prefix.length) : file;
263537
263539
  }
263538
263540
 
263539
- // ../functions-compiler/src/source-map.ts
263540
- var INTERNAL_SOURCE_PREFIX = "base44-internal:";
263541
- var USER_PREFIX = `${USER_NAMESPACE}:`;
263542
- var APP_FUNCTION_PATH = /^fn_(\d+)\/(.*)$/;
263543
- function functionSourceMap(raw, fn) {
263544
- return rewriteSources(raw, (key) => appPath(fn, key));
263545
- }
263546
- function appSourceMap(raw, functions) {
263547
- return rewriteSources(raw, (key) => {
263548
- const match = key.match(APP_FUNCTION_PATH);
263549
- const fn = match ? functions[Number(match[1])] : undefined;
263550
- return fn && match ? appPath(fn, match[2]) : undefined;
263551
- });
263552
- }
263553
- function appPath(fn, key) {
263554
- if (!Object.hasOwn(fn.files, key))
263555
- return;
263556
- return key === fn.entry && fn.entryPath ? fn.entryPath : key;
263557
- }
263558
- function rewriteSources(raw, appPathOf) {
263559
- const map = JSON.parse(raw);
263560
- map.sources = (map.sources ?? []).map((source) => {
263561
- const app = source.startsWith(USER_PREFIX) ? appPathOf(source.slice(USER_PREFIX.length)) : undefined;
263562
- return app ?? `${INTERNAL_SOURCE_PREFIX}${source}`;
263563
- });
263564
- delete map.sourceRoot;
263565
- delete map.sourcesContent;
263566
- return JSON.stringify(map);
263567
- }
263568
-
263569
263541
  // ../functions-compiler/src/tracing.ts
263570
263542
  var noopTracer = {
263571
263543
  withSpan: (_name, fn) => fn(),
@@ -263580,6 +263552,7 @@ function setSpanTags(tags) {
263580
263552
  }
263581
263553
 
263582
263554
  // ../functions-compiler/src/bundler.ts
263555
+ var NORMALIZED_MAIN_MODULE = "_bundled.mjs";
263583
263556
  var MAX_PARALLEL_COMPILES = 4;
263584
263557
  async function bundle(req) {
263585
263558
  let actor;
@@ -263600,7 +263573,7 @@ async function bundle(req) {
263600
263573
  return {
263601
263574
  ok: true,
263602
263575
  module: outcome.module,
263603
- main_module: MAIN_MODULE,
263576
+ main_module: NORMALIZED_MAIN_MODULE,
263604
263577
  warnings: outcome.warnings,
263605
263578
  handler_name: actor.handlerName,
263606
263579
  do_class_name: actor.doClassName
@@ -263614,13 +263587,12 @@ async function bundle(req) {
263614
263587
  } catch (e) {
263615
263588
  return denoCompatErrorOrThrow(e);
263616
263589
  }
263617
- const outcome = await installAndCompile(prepared, req.sourceMap ?? false);
263590
+ const outcome = await installAndCompile(prepared);
263618
263591
  if (outcome.ok) {
263619
263592
  return {
263620
263593
  ok: true,
263621
263594
  module: outcome.module,
263622
- ...outcome.map ? { source_map: functionSourceMap(outcome.map, req) } : {},
263623
- main_module: MAIN_MODULE,
263595
+ main_module: NORMALIZED_MAIN_MODULE,
263624
263596
  warnings: outcome.warnings,
263625
263597
  ...activationField(req.runtimeSecrets ?? false)
263626
263598
  };
@@ -263635,29 +263607,26 @@ async function bundleApp(req) {
263635
263607
  return result.ok ? { ...result, ...activationField(req.runtimeSecrets ?? false) } : result;
263636
263608
  }
263637
263609
  async function assembleApp(req) {
263638
- const build = {
263639
- telemetry: req.postResponseTelemetry ?? false,
263640
- runtimeSecrets: req.runtimeSecrets ?? false,
263641
- sourceMap: req.sourceMap ?? false
263642
- };
263610
+ const telemetry = req.postResponseTelemetry ?? false;
263611
+ const runtimeSecrets = req.runtimeSecrets ?? false;
263643
263612
  const entries = req.functions.map((fn, index) => ({
263644
263613
  index,
263645
263614
  fn
263646
263615
  }));
263647
263616
  let combined;
263648
263617
  try {
263649
- combined = await compileApp(entries, build);
263618
+ combined = await compileApp(entries, telemetry, runtimeSecrets);
263650
263619
  } catch (e) {
263651
263620
  if (e instanceof DenoCompatError)
263652
- return bundleAppPerFunction(entries, build);
263621
+ return bundleAppPerFunction(entries, telemetry, runtimeSecrets);
263653
263622
  throw e;
263654
263623
  }
263655
263624
  if (combined.ok) {
263656
- return appResponse(combined, allOk(entries));
263625
+ return appResponse(combined.module, allOk(entries));
263657
263626
  }
263658
263627
  const { byIndex, unattributable } = classifyAppErrors(combined.errors);
263659
263628
  if (unattributable.length > 0) {
263660
- return bundleAppPerFunction(entries, build);
263629
+ return bundleAppPerFunction(entries, telemetry, runtimeSecrets);
263661
263630
  }
263662
263631
  const functions = entries.map((e) => byIndex.has(e.index) ? { name: e.fn.name, ok: false, errors: byIndex.get(e.index) } : { name: e.fn.name, ok: true });
263663
263632
  const survivors = entries.filter((e) => !byIndex.has(e.index));
@@ -263666,42 +263635,25 @@ async function assembleApp(req) {
263666
263635
  }
263667
263636
  let rebuilt;
263668
263637
  try {
263669
- rebuilt = await compileApp(survivors, build);
263638
+ rebuilt = await compileApp(survivors, telemetry, runtimeSecrets);
263670
263639
  } catch (e) {
263671
263640
  if (e instanceof DenoCompatError)
263672
- return bundleAppPerFunction(entries, build);
263641
+ return bundleAppPerFunction(entries, telemetry, runtimeSecrets);
263673
263642
  throw e;
263674
263643
  }
263675
263644
  if (rebuilt.ok)
263676
- return appResponse(rebuilt, functions);
263677
- return bundleAppPerFunction(entries, build);
263678
- }
263679
- async function compileApp(entries, build) {
263680
- const outcome = await installAndCompile(prepareApp(entries, build.telemetry, build.runtimeSecrets), build.sourceMap);
263681
- if (!outcome.ok)
263682
- return { ok: false, errors: outcome.errors };
263683
- if (!outcome.map)
263684
- return { ok: true, module: outcome.module };
263685
- const functions = [];
263686
- for (const { index, fn } of entries)
263687
- functions[index] = fn;
263688
- return {
263689
- ok: true,
263690
- module: outcome.module,
263691
- map: appSourceMap(outcome.map, functions)
263692
- };
263645
+ return appResponse(rebuilt.module, functions);
263646
+ return bundleAppPerFunction(entries, telemetry, runtimeSecrets);
263647
+ }
263648
+ async function compileApp(entries, telemetry = false, runtimeSecrets = false) {
263649
+ const outcome = await installAndCompile(prepareApp(entries, telemetry, runtimeSecrets));
263650
+ return outcome.ok ? { ok: true, module: outcome.module } : { ok: false, errors: outcome.errors };
263693
263651
  }
263694
263652
  function allOk(entries) {
263695
263653
  return entries.map((e) => ({ name: e.fn.name, ok: true }));
263696
263654
  }
263697
- function appResponse(built, functions) {
263698
- return {
263699
- ok: true,
263700
- module: built.module,
263701
- ...built.map ? { source_map: built.map } : {},
263702
- main_module: MAIN_MODULE,
263703
- functions
263704
- };
263655
+ function appResponse(module, functions) {
263656
+ return { ok: true, module, main_module: NORMALIZED_MAIN_MODULE, functions };
263705
263657
  }
263706
263658
  function classifyAppErrors(errors) {
263707
263659
  const byIndex = new Map;
@@ -263719,19 +263671,19 @@ function classifyAppErrors(errors) {
263719
263671
  }
263720
263672
  return { byIndex, unattributable };
263721
263673
  }
263722
- async function bundleAppPerFunction(entries, build) {
263723
- const probes = await mapWithConcurrency(entries, MAX_PARALLEL_COMPILES, (entry) => probeFunction(entry, build.runtimeSecrets));
263674
+ async function bundleAppPerFunction(entries, telemetry = false, runtimeSecrets = false) {
263675
+ const probes = await mapWithConcurrency(entries, MAX_PARALLEL_COMPILES, (entry) => probeFunction(entry, runtimeSecrets));
263724
263676
  const functions = probes.map((p) => p.ok ? { name: p.entry.fn.name, ok: true } : { name: p.entry.fn.name, ok: false, errors: p.errors });
263725
263677
  const survivors = probes.filter((p) => p.ok).map((p) => p.entry);
263726
263678
  if (survivors.length === 0) {
263727
263679
  return { ok: false, module: null, functions };
263728
263680
  }
263729
- const combined = await compileApp(survivors, build);
263681
+ const combined = await compileApp(survivors, telemetry, runtimeSecrets);
263730
263682
  if (combined.ok)
263731
- return appResponse(combined, functions);
263732
- return assembleWithoutConflicting(survivors, functions, combined.errors, build);
263683
+ return appResponse(combined.module, functions);
263684
+ return assembleWithoutConflicting(survivors, functions, combined.errors, telemetry, runtimeSecrets);
263733
263685
  }
263734
- async function assembleWithoutConflicting(survivors, functions, errors, build) {
263686
+ async function assembleWithoutConflicting(survivors, functions, errors, telemetry, runtimeSecrets = false) {
263735
263687
  const failWith = (entries, items) => {
263736
263688
  for (const e of entries) {
263737
263689
  functions[e.index] = { name: e.fn.name, ok: false, errors: items };
@@ -263746,10 +263698,10 @@ async function assembleWithoutConflicting(survivors, functions, errors, build) {
263746
263698
  const blamed = survivors.filter((e) => importsConflictingPackage(e, errors));
263747
263699
  const rest = survivors.filter((e) => !blamed.includes(e));
263748
263700
  if (blamed.length > 0 && rest.length > 0) {
263749
- const rebuilt = await compileApp(rest, build);
263701
+ const rebuilt = await compileApp(rest, telemetry, runtimeSecrets);
263750
263702
  if (rebuilt.ok) {
263751
263703
  failWith(blamed, conflictErrors);
263752
- return appResponse(rebuilt, functions);
263704
+ return appResponse(rebuilt.module, functions);
263753
263705
  }
263754
263706
  failWith(blamed, conflictErrors);
263755
263707
  failWith(rest, [conflictErrors[0], ...rebuilt.errors]);
@@ -263786,11 +263738,7 @@ function escapeRegExp(s) {
263786
263738
  async function probeFunction(entry, runtimeSecrets = false) {
263787
263739
  let outcome;
263788
263740
  try {
263789
- outcome = await compileApp([entry], {
263790
- telemetry: false,
263791
- runtimeSecrets,
263792
- sourceMap: false
263793
- });
263741
+ outcome = await compileApp([entry], false, runtimeSecrets);
263794
263742
  } catch (e) {
263795
263743
  if (e instanceof DenoCompatError) {
263796
263744
  return { ok: false, entry, errors: [denoCompatErrorItem(e)] };
@@ -263820,25 +263768,20 @@ async function mapWithConcurrency(items, limit, fn) {
263820
263768
  return results;
263821
263769
  }
263822
263770
  var NODE_MODULES_FALLBACK = /ERR_MODULE_NOT_FOUND|Could not find referrer npm package/;
263823
- async function installAndCompile(prepared, sourceMap = false) {
263771
+ async function installAndCompile(prepared) {
263824
263772
  return withSpan("base44.bundler.compile", async () => {
263825
263773
  let mode = "none";
263826
- let result = await bundleToModule(prepared, mode, sourceMap);
263774
+ let result = await bundleToModule(prepared, mode);
263827
263775
  if (!result.ok && result.errors.some((e) => NODE_MODULES_FALLBACK.test(e.message))) {
263828
263776
  mode = "auto";
263829
- result = await bundleToModule(prepared, mode, sourceMap);
263777
+ result = await bundleToModule(prepared, mode);
263830
263778
  }
263831
263779
  await setSpanTags({
263832
263780
  node_modules_mode: mode,
263833
263781
  outcome: result.ok ? "ok" : "failed"
263834
263782
  });
263835
263783
  if (result.ok) {
263836
- return {
263837
- ok: true,
263838
- module: result.module,
263839
- ...result.map ? { map: result.map } : {},
263840
- warnings: result.warnings
263841
- };
263784
+ return { ok: true, module: result.module, warnings: result.warnings };
263842
263785
  }
263843
263786
  return { ok: false, stage: "esbuild", errors: result.errors };
263844
263787
  });
@@ -269855,6 +269798,374 @@ Examples:
269855
269798
  $ echo "const all = await base44.entities.Task.list()" | base44 exec --privileged`).action(execAction);
269856
269799
  }
269857
269800
 
269801
+ // src/cli/commands/import.ts
269802
+ var import_ms2 = __toESM(require_ms(), 1);
269803
+
269804
+ // src/core/session-import/api.ts
269805
+ var MAX_SESSION_BYTES = 25 * 1024 * 1024;
269806
+ var SessionImportResponseSchema = object({
269807
+ branch_id: string2(),
269808
+ branch_name: string2(),
269809
+ source: _enum(["claude_code", "codex"]),
269810
+ turn_count: number2(),
269811
+ branch_url: string2()
269812
+ }).transform((data) => ({
269813
+ branchId: data.branch_id,
269814
+ branchName: data.branch_name,
269815
+ source: data.source,
269816
+ turnCount: data.turn_count,
269817
+ branchUrl: data.branch_url
269818
+ }));
269819
+ var ErrorEnvelopeSchema = object({
269820
+ error: object({ code: string2().optional() })
269821
+ });
269822
+ var NETWORK_BLOCKED = "claude.ai is blocking Base44. In this session's environment settings, open Network access, add `app.base44.com` and `base44.app` to Allowed domains, save, and try again.";
269823
+ function messageFor(status, code, viaToken) {
269824
+ if (status === 401 && viaToken) {
269825
+ return "This import key expired or was already used. In Base Code, open Import session and copy a new prompt.";
269826
+ }
269827
+ if (status === 403) {
269828
+ return "You don't have edit access to this app, or this key was made for a different app.";
269829
+ }
269830
+ if (status === 404)
269831
+ return "Session import isn't available for this app.";
269832
+ if (status === 413)
269833
+ return "This session is over 25 MB and can't be imported.";
269834
+ if (code === "unsupported_file") {
269835
+ return "That file isn't a Claude Code or Codex session.";
269836
+ }
269837
+ if (code === "repository_mismatch") {
269838
+ return "This session is from a different repository than the app.";
269839
+ }
269840
+ if (status === 429)
269841
+ return "Too many imports. Wait a minute and try again.";
269842
+ return;
269843
+ }
269844
+ async function toImportError(error, viaToken) {
269845
+ if (!(error instanceof HTTPError)) {
269846
+ const reason = error instanceof Error ? error.message : String(error);
269847
+ return new ApiError(process.env.CLAUDE_CODE_REMOTE ? NETWORK_BLOCKED : `Couldn't reach Base44: ${reason}`, { hints: [] });
269848
+ }
269849
+ const { status } = error.response;
269850
+ const fallback = await ApiError.fromHttpError(error, "importing session");
269851
+ const envelope = ErrorEnvelopeSchema.safeParse(fallback.responseBody);
269852
+ const code = envelope.success ? envelope.data.error.code : undefined;
269853
+ const blocked = process.env.CLAUDE_CODE_REMOTE && status === 403 && typeof fallback.responseBody !== "object";
269854
+ const known = blocked ? NETWORK_BLOCKED : messageFor(status, code, viaToken);
269855
+ return new ApiError(known ?? fallback.message, {
269856
+ statusCode: status,
269857
+ requestUrl: error.request.url,
269858
+ requestMethod: error.request.method,
269859
+ requestId: fallback.requestId,
269860
+ hints: known ? [] : fallback.hints
269861
+ });
269862
+ }
269863
+ async function uploadSession(appId, content, token) {
269864
+ const form = new FormData;
269865
+ form.append("file", new Blob([content]), "session.jsonl");
269866
+ let response;
269867
+ try {
269868
+ response = token ? await distribution_default.post(new URL(`/api/apps/${appId}/imported/session-imports`, getBase44ApiUrl()), {
269869
+ body: form,
269870
+ headers: {
269871
+ Authorization: `Bearer ${token}`,
269872
+ "User-Agent": "Base44 CLI"
269873
+ },
269874
+ timeout: 180000
269875
+ }) : await getAppClient().post("imported/session-imports", {
269876
+ body: form,
269877
+ timeout: 180000
269878
+ });
269879
+ } catch (error) {
269880
+ throw await toImportError(error, Boolean(token));
269881
+ }
269882
+ const result = SessionImportResponseSchema.safeParse(await response.json());
269883
+ if (!result.success) {
269884
+ throw new SchemaValidationError("Invalid session import response from server", result.error);
269885
+ }
269886
+ return result.data;
269887
+ }
269888
+
269889
+ // src/core/session-import/sessions.ts
269890
+ import { createReadStream as createReadStream3 } from "node:fs";
269891
+ import { realpath as realpath2, rm as rm5, stat as stat8 } from "node:fs/promises";
269892
+ import { homedir as homedir5 } from "node:os";
269893
+ import { dirname as dirname29, join as join41 } from "node:path";
269894
+ import { createInterface as createInterface2 } from "node:readline";
269895
+ var claudeDir = () => process.env.CLAUDE_CONFIG_DIR || join41(homedir5(), ".claude");
269896
+ var codexDir = () => process.env.CODEX_HOME || join41(homedir5(), ".codex");
269897
+ async function scanLines(path, pick, maxLines = Number.POSITIVE_INFINITY) {
269898
+ const lines = createInterface2({ input: createReadStream3(path) });
269899
+ let count = 0;
269900
+ try {
269901
+ for await (const line of lines) {
269902
+ if (++count > maxLines)
269903
+ return;
269904
+ try {
269905
+ const found = pick(JSON.parse(line));
269906
+ if (found !== undefined)
269907
+ return found;
269908
+ } catch {}
269909
+ }
269910
+ } finally {
269911
+ lines.close();
269912
+ }
269913
+ return;
269914
+ }
269915
+ var asRecord = (value) => value && typeof value === "object" ? value : {};
269916
+ var codexCwd = (entry) => entry.type === "session_meta" ? String(asRecord(entry.payload).cwd ?? "") : undefined;
269917
+ async function newest(paths) {
269918
+ let best;
269919
+ for (const path of paths) {
269920
+ const { mtimeMs } = await stat8(path);
269921
+ if (!best || mtimeMs > best.mtime)
269922
+ best = { path, mtime: mtimeMs };
269923
+ }
269924
+ return best?.path;
269925
+ }
269926
+ async function sameDir(a, b) {
269927
+ if (a === b)
269928
+ return true;
269929
+ const [ra, rb] = await Promise.all([
269930
+ realpath2(a).catch(() => a),
269931
+ realpath2(b).catch(() => b)
269932
+ ]);
269933
+ return ra === rb;
269934
+ }
269935
+ var codexRollouts = () => globby("sessions/*/*/*/rollout-*.jsonl", {
269936
+ cwd: codexDir(),
269937
+ absolute: true
269938
+ });
269939
+ async function codexRolloutsIn(cwd) {
269940
+ const matches = [];
269941
+ for (const path of await codexRollouts()) {
269942
+ const recorded = await scanLines(path, codexCwd, 1);
269943
+ if (recorded && await sameDir(recorded, cwd))
269944
+ matches.push(path);
269945
+ }
269946
+ return matches;
269947
+ }
269948
+ async function findCurrentSession(cwd) {
269949
+ const claudeId = process.env.CLAUDE_CODE_SESSION_ID;
269950
+ if (claudeId) {
269951
+ const [path] = await globby(`projects/*/${claudeId}.jsonl`, {
269952
+ cwd: claudeDir(),
269953
+ absolute: true
269954
+ });
269955
+ return path;
269956
+ }
269957
+ const codexId = process.env.CODEX_THREAD_ID;
269958
+ if (codexId) {
269959
+ const rollouts = await codexRollouts();
269960
+ return rollouts.find((path) => path.endsWith(`-${codexId}.jsonl`));
269961
+ }
269962
+ return newest(await codexRolloutsIn(cwd));
269963
+ }
269964
+ function claudeUserText(entry) {
269965
+ if (entry.type !== "user" || entry.isMeta || entry.isSidechain)
269966
+ return;
269967
+ const content = asRecord(entry.message).content;
269968
+ return typeof content === "string" && !content.startsWith("<") ? content : undefined;
269969
+ }
269970
+ function codexUserText(entry) {
269971
+ const payload = asRecord(entry.payload);
269972
+ return entry.type === "event_msg" && payload.type === "user_message" ? String(payload.message ?? "") : undefined;
269973
+ }
269974
+ var PICKER_LIMIT = 20;
269975
+ async function listSessions(cwd) {
269976
+ const claudeFolder = cwd.replace(/[^a-zA-Z0-9]/g, "-");
269977
+ const claude = await globby(`projects/${claudeFolder}/*.jsonl`, {
269978
+ cwd: claudeDir(),
269979
+ absolute: true
269980
+ });
269981
+ const candidates = [
269982
+ ...claude.map((path) => ({ tool: "claude_code", path })),
269983
+ ...(await codexRolloutsIn(cwd)).map((path) => ({
269984
+ tool: "codex",
269985
+ path
269986
+ }))
269987
+ ];
269988
+ const dated = await Promise.all(candidates.map(async (c) => ({
269989
+ ...c,
269990
+ updatedAt: (await stat8(c.path)).mtime
269991
+ })));
269992
+ dated.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime());
269993
+ const sessions = [];
269994
+ for (const candidate of dated.slice(0, PICKER_LIMIT)) {
269995
+ const firstMessage = await scanLines(candidate.path, candidate.tool === "claude_code" ? claudeUserText : codexUserText);
269996
+ if (firstMessage)
269997
+ sessions.push({ ...candidate, firstMessage });
269998
+ }
269999
+ return sessions;
270000
+ }
270001
+ var SESSION_ID = /session_[A-Za-z0-9]+/;
270002
+ function parseSessionLink(link) {
270003
+ if (/cshk_/.test(link) || !SESSION_ID.test(link)) {
270004
+ throw new InvalidInputError(`That isn't a claude.ai session address. Copy it from your browser's address bar (not "Copy link").`, { hints: [] });
270005
+ }
270006
+ return link.match(SESSION_ID)[0];
270007
+ }
270008
+ var TELEPORT_PROMPT = "Reply with OK.";
270009
+ var TELEPORT_NOTE = "This session is being continued from another machine";
270010
+ function parseLine(line) {
270011
+ try {
270012
+ return asRecord(JSON.parse(line));
270013
+ } catch {
270014
+ return {};
270015
+ }
270016
+ }
270017
+ function stripTeleportExchange(content) {
270018
+ const lines = content.split(`
270019
+ `);
270020
+ const entries = lines.map(parseLine);
270021
+ const userText = (entry) => entry.type === "user" ? asRecord(entry.message).content : undefined;
270022
+ let end = lines.length;
270023
+ for (let i = lines.length - 1;i >= 0; i--) {
270024
+ if (userText(entries[i] ?? {}) === TELEPORT_PROMPT) {
270025
+ end = i;
270026
+ break;
270027
+ }
270028
+ }
270029
+ return lines.slice(0, end).filter((_, i) => {
270030
+ const entry = entries[i] ?? {};
270031
+ const text = userText(entry);
270032
+ const queued = entry.type === "queue-operation" && entry.content === TELEPORT_PROMPT;
270033
+ const note = typeof text === "string" && text.startsWith(TELEPORT_NOTE);
270034
+ return !queued && !note;
270035
+ }).join(`
270036
+ `);
270037
+ }
270038
+ var NEEDS_CLAUDE = "Claude Code must be installed and signed in to the same claude.ai account to import a claude.ai session.";
270039
+ async function teleportSession(sessionId, cwd) {
270040
+ const origin = await execa("git", ["remote", "get-url", "origin"], {
270041
+ cwd,
270042
+ reject: false
270043
+ });
270044
+ if (origin.exitCode !== 0 || !origin.stdout) {
270045
+ throw new InvalidInputError("Run this from a folder with the app's GitHub repository, so the session can be checked out.");
270046
+ }
270047
+ const tmp = await $dir({ unsafeCleanup: true });
270048
+ const repo = join41(tmp.path, "repo");
270049
+ let projectFolder;
270050
+ try {
270051
+ await execa("git", ["clone", "--quiet", origin.stdout, repo]);
270052
+ const repoReal = await realpath2(repo);
270053
+ const startedAt = Date.now();
270054
+ const claudeBin = getTestOverrides()?.claudeBin ?? "claude";
270055
+ try {
270056
+ await execa(claudeBin, ["--teleport", sessionId, "-p", TELEPORT_PROMPT], {
270057
+ cwd: repo,
270058
+ stdin: "ignore"
270059
+ });
270060
+ } catch {
270061
+ throw new DependencyNotFoundError(NEEDS_CLAUDE, { hints: [] });
270062
+ }
270063
+ const fresh = [];
270064
+ for (const path of await globby("projects/*/*.jsonl", {
270065
+ cwd: claudeDir(),
270066
+ absolute: true
270067
+ })) {
270068
+ if ((await stat8(path)).mtimeMs < startedAt)
270069
+ continue;
270070
+ const sessionCwd = await scanLines(path, (entry) => typeof entry.cwd === "string" ? entry.cwd : undefined, 50);
270071
+ if (sessionCwd === repo || sessionCwd === repoReal)
270072
+ fresh.push(path);
270073
+ }
270074
+ const file = await newest(fresh);
270075
+ if (!file)
270076
+ throw new DependencyNotFoundError(NEEDS_CLAUDE, { hints: [] });
270077
+ projectFolder = dirname29(file);
270078
+ return stripTeleportExchange((await readFile(file)).toString("utf8"));
270079
+ } finally {
270080
+ if (projectFolder)
270081
+ await rm5(projectFolder, { recursive: true, force: true });
270082
+ await tmp.cleanup();
270083
+ }
270084
+ }
270085
+
270086
+ // src/cli/commands/import.ts
270087
+ var TOOL_LABELS = {
270088
+ claude_code: "Claude Code",
270089
+ codex: "Codex"
270090
+ };
270091
+ async function pickSession(cwd) {
270092
+ const sessions = await listSessions(cwd);
270093
+ if (sessions.length === 0) {
270094
+ throw new InvalidInputError("No Claude Code or Codex sessions found in this folder. Pass --file <path>.");
270095
+ }
270096
+ const choice = await Je({
270097
+ message: "Which session do you want to continue in Base Code?",
270098
+ options: sessions.map((session) => ({
270099
+ value: session.path,
270100
+ label: session.firstMessage.replace(/\s+/g, " ").slice(0, 70),
270101
+ hint: `${TOOL_LABELS[session.tool]}, ${import_ms2.default(Date.now() - session.updatedAt.getTime())} ago`
270102
+ }))
270103
+ });
270104
+ if (Ct(choice)) {
270105
+ Ne("Operation cancelled.");
270106
+ throw new CLIExitError(0);
270107
+ }
270108
+ return choice;
270109
+ }
270110
+ async function readSession(ctx, link, options) {
270111
+ const cwd = process.cwd();
270112
+ if (options.file)
270113
+ return readFile(options.file);
270114
+ if (link) {
270115
+ const sessionId = parseSessionLink(link);
270116
+ const content = await ctx.runTask("Downloading the claude.ai session", () => teleportSession(sessionId, cwd));
270117
+ return Buffer.from(content);
270118
+ }
270119
+ if (options.current) {
270120
+ const path = await findCurrentSession(cwd);
270121
+ if (!path) {
270122
+ throw new InvalidInputError("Couldn't find the current session. Run this from inside Claude Code or Codex, or pass --file <path>.", { hints: [] });
270123
+ }
270124
+ return readFile(path);
270125
+ }
270126
+ if (ctx.isNonInteractive || ctx.jsonMode) {
270127
+ throw new InvalidInputError("Choose a session: pass --current, a claude.ai session link, or --file <path>.");
270128
+ }
270129
+ return readFile(await pickSession(cwd));
270130
+ }
270131
+ async function importAction(ctx, link, options, command) {
270132
+ ctx.errorReporter.setContext({
270133
+ command: {
270134
+ name: "import",
270135
+ args: link ? ["[not reported]"] : [],
270136
+ options: {
270137
+ ...command.opts(),
270138
+ ...options.token ? { token: "[not reported]" } : {}
270139
+ }
270140
+ }
270141
+ });
270142
+ const chosen = [link, options.current, options.file].filter(Boolean).length;
270143
+ if (chosen > 1) {
270144
+ throw new InvalidInputError("Pass only one of: a session link, --current, or --file.");
270145
+ }
270146
+ const appId = requireApp(ctx).id;
270147
+ const content = await readSession(ctx, link, options);
270148
+ if (content.length > MAX_SESSION_BYTES) {
270149
+ throw new InvalidInputError("This session is over 25 MB and can't be imported.", { hints: [] });
270150
+ }
270151
+ if (await hasUnpushedWork(process.cwd())) {
270152
+ ctx.log.warn("Base Code only sees what's on GitHub. Push your changes so the new branch has them.");
270153
+ }
270154
+ if (!options.token)
270155
+ await ensureAuth(ctx);
270156
+ ctx.log.info("This uploads the full conversation to Base Code.");
270157
+ const imported = await ctx.runTask("Importing session", () => uploadSession(appId, content, options.token));
270158
+ const url = `${getBase44ApiUrl()}${imported.branchUrl}`;
270159
+ return {
270160
+ outroMessage: `✓ Imported ${imported.turnCount} messages from ${TOOL_LABELS[imported.source]} into branch "${imported.branchName}".
270161
+ Open it: ${url}`,
270162
+ stdout: ctx.jsonMode ? toJsonStdout({ ...imported, url }) : undefined
270163
+ };
270164
+ }
270165
+ function getImportCommand() {
270166
+ return new Base44Command("import", { requireAuth: false }).description("Continue a Claude Code or Codex session in a new Base Code branch").argument("[session-link]", "A claude.ai session address (https://claude.ai/code/session_…)").option("--current", "Import the session this command runs inside").option("--file <path>", "Import this session file as is").option("--token <key>", "One-time import key from Base Code (no login needed)").action(importAction);
270167
+ }
270168
+
269858
270169
  // src/cli/commands/project/eject.ts
269859
270170
  import { resolve as resolve20 } from "node:path";
269860
270171
  var import_kebabCase2 = __toESM(require_kebabCase(), 1);
@@ -270018,6 +270329,7 @@ function createProgram(context) {
270018
270329
  program.addCommand(getExecCommand());
270019
270330
  program.addCommand(getDevCommand());
270020
270331
  program.addCommand(getLogsCommand());
270332
+ program.addCommand(getImportCommand());
270021
270333
  return program;
270022
270334
  }
270023
270335
 
@@ -270026,7 +270338,7 @@ var import_detect_agent = __toESM(require_dist5(), 1);
270026
270338
  import { release, type } from "node:os";
270027
270339
 
270028
270340
  // ../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
270029
- import { dirname as dirname29, posix, sep as sep2 } from "path";
270341
+ import { dirname as dirname30, posix, sep as sep2 } from "path";
270030
270342
  function createModulerModifier() {
270031
270343
  const getModuleFromFileName = createGetModuleFromFilename();
270032
270344
  return async (frames) => {
@@ -270035,7 +270347,7 @@ function createModulerModifier() {
270035
270347
  return frames;
270036
270348
  };
270037
270349
  }
270038
- function createGetModuleFromFilename(basePath = process.argv[1] ? dirname29(process.argv[1]) : process.cwd(), isWindows = sep2 === "\\") {
270350
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname30(process.argv[1]) : process.cwd(), isWindows = sep2 === "\\") {
270039
270351
  const normalizedBase = isWindows ? normalizeWindowsPath2(basePath) : basePath;
270040
270352
  return (filename) => {
270041
270353
  if (!filename)
@@ -272070,8 +272382,8 @@ class ReduceableCache {
272070
272382
  }
272071
272383
  }
272072
272384
  // ../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
272073
- import { createReadStream as createReadStream3 } from "node:fs";
272074
- import { createInterface as createInterface2 } from "node:readline";
272385
+ import { createReadStream as createReadStream4 } from "node:fs";
272386
+ import { createInterface as createInterface3 } from "node:readline";
272075
272387
  var LRU_FILE_CONTENTS_CACHE = new ReduceableCache(25);
272076
272388
  var LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
272077
272389
  var DEFAULT_LINES_OF_CONTEXT = 7;
@@ -272114,8 +272426,8 @@ async function addSourceContext(frames) {
272114
272426
  }
272115
272427
  function getContextLinesFromFile(path, ranges, output) {
272116
272428
  return new Promise((resolve) => {
272117
- const stream = createReadStream3(path);
272118
- const lineReaded = createInterface2({
272429
+ const stream = createReadStream4(path);
272430
+ const lineReaded = createInterface3({
272119
272431
  input: stream
272120
272432
  });
272121
272433
  function destroyStreamAndResolve() {
@@ -274024,9 +274336,9 @@ function addCommandInfoToErrorReporter(program, errorReporter) {
274024
274336
  });
274025
274337
  }
274026
274338
  // src/cli/index.ts
274027
- var __dirname4 = dirname30(fileURLToPath7(import.meta.url));
274339
+ var __dirname4 = dirname31(fileURLToPath7(import.meta.url));
274028
274340
  async function runCLI(options) {
274029
- ensureNpmAssets(join41(__dirname4, "../assets"));
274341
+ ensureNpmAssets(join42(__dirname4, "../assets"));
274030
274342
  const errorReporter = new ErrorReporter;
274031
274343
  errorReporter.registerProcessErrorHandlers();
274032
274344
  const jsonMode = process.argv.includes("--json");
@@ -274065,4 +274377,4 @@ export {
274065
274377
  runCLI
274066
274378
  };
274067
274379
 
274068
- //# debugId=3CA0B8062C899A1564756E2164756E21
274380
+ //# debugId=A7200797A10A03A864756E2164756E21