@lotics/cli 0.102.0 → 0.103.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/README.md CHANGED
@@ -239,9 +239,10 @@ lotics app agent run app_abc recognize --json # full run summar
239
239
  lotics app agent run app_abc recognize --session cli-123 '{}' # continue an existing thread
240
240
 
241
241
  # Dev-link @lotics/ui to packages/ui/src for live HMR (Vite alias; deploy bundles it)
242
- lotics ui link card # monorepo: packages/ui/src found automatically
243
- lotics ui link card --ui-src /abs/monorepo/packages/ui/src # external app (e.g. ~/lotics_apps)
244
- lotics ui link card --remove # finalize: PR + publish, then drop the alias
242
+ # Dev-link @lotics/ui to a monorepo checkout for ONE command — nothing is written to disk
243
+ LOTICS_UI_SRC=/abs/monorepo/packages/ui/src lotics app dev
244
+ LOTICS_UI_SRC=/abs/monorepo/packages/ui/src lotics app deploy -m "..." # warns: bundles YOUR kit copy
245
+ lotics app dev # unset ⇒ @lotics/ui resolves from node_modules again
245
246
  ```
246
247
 
247
248
  `app codegen` reads `package.json#lotics.queries` to decide which tables to put in `app_fields.ts`; widen the set with `package.json#lotics.codegen.tables` (an array of `tbl_…` ids) for tables the app only writes via workflows.
@@ -25066,6 +25066,7 @@ ${e.toString()}`);
25066
25066
  this._byDepthAndTag = /* @__PURE__ */ new Map();
25067
25067
  this._wildcardByDepth = /* @__PURE__ */ new Map();
25068
25068
  this._deepWildcards = [];
25069
+ this._deepByTerminalTag = /* @__PURE__ */ new Map();
25069
25070
  this._patterns = /* @__PURE__ */ new Set();
25070
25071
  this._sealed = false;
25071
25072
  }
@@ -25090,7 +25091,14 @@ ${e.toString()}`);
25090
25091
  if (this._patterns.has(expression.pattern)) return this;
25091
25092
  this._patterns.add(expression.pattern);
25092
25093
  if (expression.hasDeepWildcard()) {
25093
- this._deepWildcards.push(expression);
25094
+ const lastSeg2 = expression.segments[expression.segments.length - 1];
25095
+ if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") {
25096
+ const tag2 = lastSeg2.tag;
25097
+ if (!this._deepByTerminalTag.has(tag2)) this._deepByTerminalTag.set(tag2, []);
25098
+ this._deepByTerminalTag.get(tag2).push(expression);
25099
+ } else {
25100
+ this._deepWildcards.push(expression);
25101
+ }
25094
25102
  return this;
25095
25103
  }
25096
25104
  const depth = expression.length;
@@ -25208,6 +25216,12 @@ ${e.toString()}`);
25208
25216
  if (matcher.matches(wildcardBucket[i3])) return wildcardBucket[i3];
25209
25217
  }
25210
25218
  }
25219
+ const deepBucket = this._deepByTerminalTag.get(tag);
25220
+ if (deepBucket) {
25221
+ for (let i3 = 0; i3 < deepBucket.length; i3++) {
25222
+ if (matcher.matches(deepBucket[i3])) return deepBucket[i3];
25223
+ }
25224
+ }
25211
25225
  for (let i3 = 0; i3 < this._deepWildcards.length; i3++) {
25212
25226
  if (matcher.matches(this._deepWildcards[i3])) return this._deepWildcards[i3];
25213
25227
  }
@@ -25267,6 +25281,24 @@ ${e.toString()}`);
25267
25281
  const current = path[path.length - 1];
25268
25282
  return current.values !== void 0 && attrName in current.values;
25269
25283
  }
25284
+ /**
25285
+ * Get the value of a "kept" attribute from the nearest ancestor (or
25286
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
25287
+ * @param {string} attrName
25288
+ * @returns {*}
25289
+ */
25290
+ getAnyParentAttr(attrName) {
25291
+ return this._matcher.getAnyParentAttr(attrName);
25292
+ }
25293
+ /**
25294
+ * Check whether any ancestor (or the current node) kept the given
25295
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
25296
+ * @param {string} attrName
25297
+ * @returns {boolean}
25298
+ */
25299
+ hasAnyParentAttr(attrName) {
25300
+ return this._matcher.hasAnyParentAttr(attrName);
25301
+ }
25270
25302
  /**
25271
25303
  * Get current node's sibling position (child index in parent).
25272
25304
  * @returns {number}
@@ -25345,30 +25377,32 @@ ${e.toString()}`);
25345
25377
  this.siblingStacks = [];
25346
25378
  this._pathStringCache = null;
25347
25379
  this._view = new MatcherView(this);
25380
+ this._keptAttrs = [];
25348
25381
  }
25349
25382
  /**
25350
25383
  * Push a new tag onto the path.
25351
25384
  * @param {string} tagName
25352
25385
  * @param {Object|null} [attrValues=null]
25353
25386
  * @param {string|null} [namespace=null]
25387
+ * @param {Object|null} [options=null]
25388
+ * @param {string[]} [options.keep] - Names of attributes (from attrValues)
25354
25389
  */
25355
- push(tagName, attrValues = null, namespace = null) {
25390
+ push(tagName, attrValues = null, namespace = null, options = null) {
25356
25391
  this._pathStringCache = null;
25357
25392
  if (this.path.length > 0) {
25358
25393
  this.path[this.path.length - 1].values = void 0;
25359
25394
  }
25360
25395
  const currentLevel = this.path.length;
25361
- if (!this.siblingStacks[currentLevel]) {
25362
- this.siblingStacks[currentLevel] = /* @__PURE__ */ new Map();
25396
+ let level2 = this.siblingStacks[currentLevel];
25397
+ if (!level2) {
25398
+ level2 = { counts: /* @__PURE__ */ new Map(), total: 0 };
25399
+ this.siblingStacks[currentLevel] = level2;
25363
25400
  }
25364
- const siblings = this.siblingStacks[currentLevel];
25365
25401
  const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
25366
- const counter = siblings.get(siblingKey) || 0;
25367
- let position = 0;
25368
- for (const count of siblings.values()) {
25369
- position += count;
25370
- }
25371
- siblings.set(siblingKey, counter + 1);
25402
+ const counter = level2.counts.get(siblingKey) || 0;
25403
+ const position = level2.total;
25404
+ level2.counts.set(siblingKey, counter + 1);
25405
+ level2.total++;
25372
25406
  const node = {
25373
25407
  tag: tagName,
25374
25408
  position,
@@ -25381,6 +25415,16 @@ ${e.toString()}`);
25381
25415
  node.values = attrValues;
25382
25416
  }
25383
25417
  this.path.push(node);
25418
+ const depth = this.path.length;
25419
+ const keep = options !== null ? options.keep : null;
25420
+ if (keep !== null && keep !== void 0 && keep.length > 0 && attrValues) {
25421
+ for (let i3 = 0; i3 < keep.length; i3++) {
25422
+ const name = keep[i3];
25423
+ if (attrValues[name] !== void 0) {
25424
+ this._keptAttrs.push({ depth, name, value: attrValues[name] });
25425
+ }
25426
+ }
25427
+ }
25384
25428
  }
25385
25429
  /**
25386
25430
  * Pop the last tag from the path.
@@ -25393,6 +25437,10 @@ ${e.toString()}`);
25393
25437
  if (this.siblingStacks.length > this.path.length + 1) {
25394
25438
  this.siblingStacks.length = this.path.length + 1;
25395
25439
  }
25440
+ const poppedDepth = this.path.length + 1;
25441
+ while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) {
25442
+ this._keptAttrs.pop();
25443
+ }
25396
25444
  return node;
25397
25445
  }
25398
25446
  /**
@@ -25441,6 +25489,36 @@ ${e.toString()}`);
25441
25489
  const current = this.path[this.path.length - 1];
25442
25490
  return current.values !== void 0 && attrName in current.values;
25443
25491
  }
25492
+ /**
25493
+ * Get the value of a "kept" attribute from the nearest ancestor (or
25494
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
25495
+ * Unlike getAttrValue(), this works regardless of how deep the path has
25496
+ * gone since the attribute was pushed — but only for attribute names that
25497
+ * were explicitly marked with `keep` at push time. Cost is proportional to
25498
+ * the number of currently-kept attributes (typically 0-3), not path depth.
25499
+ * @param {string} attrName
25500
+ * @returns {*} the value, or undefined if no ancestor kept this attribute
25501
+ */
25502
+ getAnyParentAttr(attrName) {
25503
+ const kept = this._keptAttrs;
25504
+ for (let i3 = kept.length - 1; i3 >= 0; i3--) {
25505
+ if (kept[i3].name === attrName) return kept[i3].value;
25506
+ }
25507
+ return void 0;
25508
+ }
25509
+ /**
25510
+ * Check whether any ancestor (or the current node) kept the given
25511
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
25512
+ * @param {string} attrName
25513
+ * @returns {boolean}
25514
+ */
25515
+ hasAnyParentAttr(attrName) {
25516
+ const kept = this._keptAttrs;
25517
+ for (let i3 = kept.length - 1; i3 >= 0; i3--) {
25518
+ if (kept[i3].name === attrName) return true;
25519
+ }
25520
+ return false;
25521
+ }
25444
25522
  /**
25445
25523
  * Get current node's sibling position (child index in parent).
25446
25524
  * @returns {number}
@@ -25509,6 +25587,7 @@ ${e.toString()}`);
25509
25587
  this._pathStringCache = null;
25510
25588
  this.path = [];
25511
25589
  this.siblingStacks = [];
25590
+ this._keptAttrs = [];
25512
25591
  }
25513
25592
  /**
25514
25593
  * Match current path against an Expression.
@@ -25632,7 +25711,8 @@ ${e.toString()}`);
25632
25711
  snapshot() {
25633
25712
  return {
25634
25713
  path: this.path.map((node) => ({ ...node })),
25635
- siblingStacks: this.siblingStacks.map((map3) => new Map(map3))
25714
+ siblingStacks: this.siblingStacks.map((level2) => level2 ? { counts: new Map(level2.counts), total: level2.total } : level2),
25715
+ keptAttrs: this._keptAttrs.map((entry) => ({ ...entry }))
25636
25716
  };
25637
25717
  }
25638
25718
  /**
@@ -25642,7 +25722,8 @@ ${e.toString()}`);
25642
25722
  restore(snapshot) {
25643
25723
  this._pathStringCache = null;
25644
25724
  this.path = snapshot.path.map((node) => ({ ...node }));
25645
- this.siblingStacks = snapshot.siblingStacks.map((map3) => new Map(map3));
25725
+ this.siblingStacks = snapshot.siblingStacks.map((level2) => level2 ? { counts: new Map(level2.counts), total: level2.total } : level2);
25726
+ this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry }));
25646
25727
  }
25647
25728
  /**
25648
25729
  * Return the read-only {@link MatcherView} for this matcher.
package/dist/src/cli.js CHANGED
@@ -45532,7 +45532,23 @@ export default defineConfig({
45532
45532
  // is safe. Define both so dev and the deployed build behave identically.
45533
45533
  define: { __DEV__: "false", global: "globalThis" },
45534
45534
  resolve: {
45535
- alias: [{ find: "react-native", replacement: "react-native-web" }],
45535
+ // \`LOTICS_UI_SRC\` dev-links @lotics/ui to a monorepo checkout, so kit edits
45536
+ // go live (HMR) and bundle on deploy without a publish round-trip:
45537
+ // LOTICS_UI_SRC=/abs/path/to/packages/ui/src lotics app dev
45538
+ // Unset \u21D2 the kit resolves from node_modules as normal. It lives in the ENV,
45539
+ // never in this file: the link used to be written here by \`lotics ui link\`
45540
+ // and removed by \`--remove\`, which is a regex editing TypeScript \u2014 it twice
45541
+ // took the react-native alias below with it and left the app unable to build.
45542
+ // State that only exists for the length of one command belongs in the command.
45543
+ // VITE ONLY: \`tsc\` still resolves @lotics/ui from node_modules (the kit's
45544
+ // src is RN-Web and cannot typecheck inside an app), so typecheck the kit in
45545
+ // packages/ui and let the publish restore this app's own typecheck.
45546
+ alias: [
45547
+ ...(process.env.LOTICS_UI_SRC
45548
+ ? [{ find: /^@lotics\\/ui\\/(.+)$/, replacement: \`\${process.env.LOTICS_UI_SRC}/$1\` }]
45549
+ : []),
45550
+ { find: "react-native", replacement: "react-native-web" },
45551
+ ],
45536
45552
  // \`.web.js\` resolves the web build of RN packages that ship \`X.js\` (native)
45537
45553
  // beside \`X.web.js\` (web) \u2014 e.g. @react-native-picker/picker, whose compiled
45538
45554
  // \`Picker.web.js\` renders a real <select>. Without it the extensionless
@@ -70492,6 +70508,29 @@ function writeBindingAppFields(projectDir, binding) {
70492
70508
  ensureAppVitestSetup(projectDir);
70493
70509
  return file2;
70494
70510
  }
70511
+ function warnIfDeployingLinkedKit(projectDir) {
70512
+ const uiSrc = process.env.LOTICS_UI_SRC;
70513
+ if (!uiSrc) return;
70514
+ const viteConfigPath = path5.join(projectDir, "vite.config.ts");
70515
+ if (!fs4.existsSync(viteConfigPath)) return;
70516
+ if (!fs4.readFileSync(viteConfigPath, "utf-8").includes("LOTICS_UI_SRC")) return;
70517
+ console.error(
70518
+ `\u26A0 LOTICS_UI_SRC is set \u2014 this deploy bundles @lotics/ui from ${uiSrc}, NOT the published package. The deployed app will run kit code that exists only on this machine. Unset it and re-deploy once the kit change is published if that is not what you want.`
70519
+ );
70520
+ }
70521
+ function warnIfDevLinkIgnored(projectDir) {
70522
+ const uiSrc = process.env.LOTICS_UI_SRC;
70523
+ if (!uiSrc) return;
70524
+ const viteConfigPath = path5.join(projectDir, "vite.config.ts");
70525
+ if (!fs4.existsSync(viteConfigPath)) return;
70526
+ if (fs4.readFileSync(viteConfigPath, "utf-8").includes("LOTICS_UI_SRC")) return;
70527
+ console.error(
70528
+ `\u26A0 LOTICS_UI_SRC is set but vite.config.ts never reads it \u2014 @lotics/ui will still resolve from node_modules, so kit edits will NOT appear. Add the dev-link entry to \`resolve.alias\` (refresh vite.config.ts from the starter, or paste):
70529
+ ...(process.env.LOTICS_UI_SRC
70530
+ ? [{ find: /^@lotics\\/ui\\/(.+)$/, replacement: \`\${process.env.LOTICS_UI_SRC}/$1\` }]
70531
+ : []),`
70532
+ );
70533
+ }
70495
70534
  function ensureAppVitestSetup(projectDir) {
70496
70535
  const setupPath = path5.join(projectDir, VITEST_SETUP_FILENAME);
70497
70536
  if (!fs4.existsSync(setupPath)) {
@@ -70781,6 +70820,7 @@ function readAppSourceText(projectDir) {
70781
70820
  async function appDeploy(client, args) {
70782
70821
  const projectDir = path5.resolve(args.projectDir ?? process.cwd());
70783
70822
  const meta3 = readAppMeta(projectDir);
70823
+ warnIfDeployingLinkedKit(projectDir);
70784
70824
  const sourceText = readAppSourceText(projectDir);
70785
70825
  const called = calledAppAliases(sourceText);
70786
70826
  if (called.dynamic.length > 0) {
@@ -70943,6 +70983,7 @@ function warnIfUnboundAliases(app, called) {
70943
70983
  async function appDev(client, args) {
70944
70984
  const projectDir = path5.resolve(args.projectDir ?? process.cwd());
70945
70985
  const meta3 = readAppMeta(projectDir);
70986
+ warnIfDevLinkIgnored(projectDir);
70946
70987
  writeAppDts(projectDir, { workflows: meta3.workflows, queries: meta3.queries, agents: meta3.agents });
70947
70988
  const app = await client.getApp(meta3.app_id);
70948
70989
  const handle = await startDevServer({
@@ -71370,80 +71411,6 @@ All ${results.length} workflow bodies parse and type-check clean.`) + `
71370
71411
  ${totalErrors} error${totalErrors === 1 ? "" : "s"} across ${results.length - passed} of ${results.length} ${results.length === 1 ? "body" : "bodies"}.`
71371
71412
  );
71372
71413
  }
71373
- function findUiSrcDir(start) {
71374
- let dir = path5.resolve(start);
71375
- for (; ; ) {
71376
- const candidate = path5.join(dir, "packages", "ui", "src");
71377
- if (fs4.existsSync(candidate) && fs4.statSync(candidate).isDirectory()) return candidate;
71378
- const parent = path5.dirname(dir);
71379
- if (parent === dir) return null;
71380
- dir = parent;
71381
- }
71382
- }
71383
- var UI_ALIAS_FIND_SOURCE = String.raw`/^@lotics\/ui\/(.+)$/`;
71384
- function appUiLink(args) {
71385
- const projectDir = path5.resolve(args.projectDir ?? process.cwd());
71386
- const viteConfigPath = path5.join(projectDir, "vite.config.ts");
71387
- if (!fs4.existsSync(viteConfigPath)) {
71388
- throw new Error(
71389
- `No vite.config.ts at ${projectDir}. Run inside a 'lotics app' project directory.`
71390
- );
71391
- }
71392
- const explicit = args.uiSrc ?? process.env.LOTICS_UI_SRC;
71393
- const uiSrc = explicit ? path5.resolve(explicit) : findUiSrcDir(projectDir);
71394
- if (!uiSrc || !fs4.existsSync(uiSrc) || !fs4.statSync(uiSrc).isDirectory()) {
71395
- throw new Error(
71396
- explicit ? `--ui-src / LOTICS_UI_SRC points at '${explicit}', which is not a directory. Pass the absolute path to the monorepo's packages/ui/src.` : "Cannot find packages/ui/src by walking up from this directory. For an EXTERNAL app (consuming @lotics/ui from npm), pass --ui-src=<abs path to packages/ui/src> or set LOTICS_UI_SRC; inside a monorepo checkout it is found automatically."
71397
- );
71398
- }
71399
- const hasComponent = fs4.existsSync(path5.join(uiSrc, `${args.component}.tsx`)) || fs4.existsSync(path5.join(uiSrc, `${args.component}.ts`)) || fs4.existsSync(path5.join(uiSrc, args.component));
71400
- if (!hasComponent) {
71401
- throw new Error(
71402
- `No '@lotics/ui/${args.component}' under ${uiSrc} (expected ${args.component}.tsx/.ts). Check the component name.`
71403
- );
71404
- }
71405
- const source = fs4.readFileSync(viteConfigPath, "utf-8");
71406
- const aliasEntry = `{ find: ${UI_ALIAS_FIND_SOURCE}, replacement: ${JSON.stringify(`${uiSrc}/$1`)} },`;
71407
- const alreadyLinked = source.includes(UI_ALIAS_FIND_SOURCE);
71408
- if (args.remove) {
71409
- if (!alreadyLinked) {
71410
- console.error("No @lotics/ui dev-link alias present \u2014 nothing to remove.");
71411
- return;
71412
- }
71413
- const stripped = source.replace(
71414
- new RegExp(
71415
- `\\n?[ \\t]*\\{ find: ${escapeRegExp(UI_ALIAS_FIND_SOURCE)}, ` + // The replacement is a JSON-encoded path, so it cannot contain an
71416
- // unescaped quote — bounded, rather than greedy to end of line.
71417
- String.raw`replacement: "(?:[^"\\]|\\.)*" \},`
71418
- ),
71419
- ""
71420
- );
71421
- fs4.writeFileSync(viteConfigPath, stripped);
71422
- console.error(`Removed the @lotics/ui dev-link alias from ${viteConfigPath}.`);
71423
- console.error("Restart `lotics app dev` and rm -rf node_modules/.vite to clear cached modules.");
71424
- return;
71425
- }
71426
- if (alreadyLinked) {
71427
- console.error(`@lotics/ui is already dev-linked in ${viteConfigPath}.`);
71428
- return;
71429
- }
71430
- const aliasMatch = /resolve\s*:\s*\{[\s\S]*?alias\s*:\s*\[/.exec(source);
71431
- if (!aliasMatch) {
71432
- throw new Error(
71433
- `Could not find a resolve.alias array literal in ${viteConfigPath}. Refresh vite.config.ts from the starter (packages/sdk/src/starter_template.ts) and retry.`
71434
- );
71435
- }
71436
- const insertAt = aliasMatch.index + aliasMatch[0].length;
71437
- const updated = `${source.slice(0, insertAt)}
71438
- ${aliasEntry}${source.slice(insertAt)}`;
71439
- fs4.writeFileSync(viteConfigPath, updated);
71440
- console.error(`Dev-linked @lotics/ui \u2192 ${uiSrc} in ${viteConfigPath}.`);
71441
- console.error("Restart `lotics app dev` and rm -rf node_modules/.vite to clear cached modules.");
71442
- console.error("Finalize: PR the packages/ui change \u2192 publish \u2192 `lotics ui link <component> --remove` + bump the app's dep.");
71443
- }
71444
- function escapeRegExp(s) {
71445
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
71446
- }
71447
71414
 
71448
71415
  // src/args.ts
71449
71416
  function parseArgs(argv) {
@@ -71455,7 +71422,6 @@ function parseArgs(argv) {
71455
71422
  apiKey: void 0,
71456
71423
  workspace: void 0,
71457
71424
  viewAs: void 0,
71458
- uiSrc: void 0,
71459
71425
  name: void 0,
71460
71426
  description: void 0,
71461
71427
  from: void 0,
@@ -71502,9 +71468,6 @@ function parseArgs(argv) {
71502
71468
  case "--view-as":
71503
71469
  flags.viewAs = argv[++i2];
71504
71470
  break;
71505
- case "--ui-src":
71506
- flags.uiSrc = argv[++i2];
71507
- break;
71508
71471
  case "--name":
71509
71472
  flags.name = argv[++i2];
71510
71473
  break;
@@ -74264,6 +74227,7 @@ var ExpressionSet = class {
74264
74227
  this._byDepthAndTag = /* @__PURE__ */ new Map();
74265
74228
  this._wildcardByDepth = /* @__PURE__ */ new Map();
74266
74229
  this._deepWildcards = [];
74230
+ this._deepByTerminalTag = /* @__PURE__ */ new Map();
74267
74231
  this._patterns = /* @__PURE__ */ new Set();
74268
74232
  this._sealed = false;
74269
74233
  }
@@ -74288,7 +74252,14 @@ var ExpressionSet = class {
74288
74252
  if (this._patterns.has(expression.pattern)) return this;
74289
74253
  this._patterns.add(expression.pattern);
74290
74254
  if (expression.hasDeepWildcard()) {
74291
- this._deepWildcards.push(expression);
74255
+ const lastSeg2 = expression.segments[expression.segments.length - 1];
74256
+ if (lastSeg2 && lastSeg2.type !== "deep-wildcard" && lastSeg2.tag !== "*") {
74257
+ const tag2 = lastSeg2.tag;
74258
+ if (!this._deepByTerminalTag.has(tag2)) this._deepByTerminalTag.set(tag2, []);
74259
+ this._deepByTerminalTag.get(tag2).push(expression);
74260
+ } else {
74261
+ this._deepWildcards.push(expression);
74262
+ }
74292
74263
  return this;
74293
74264
  }
74294
74265
  const depth = expression.length;
@@ -74406,6 +74377,12 @@ var ExpressionSet = class {
74406
74377
  if (matcher.matches(wildcardBucket[i2])) return wildcardBucket[i2];
74407
74378
  }
74408
74379
  }
74380
+ const deepBucket = this._deepByTerminalTag.get(tag);
74381
+ if (deepBucket) {
74382
+ for (let i2 = 0; i2 < deepBucket.length; i2++) {
74383
+ if (matcher.matches(deepBucket[i2])) return deepBucket[i2];
74384
+ }
74385
+ }
74409
74386
  for (let i2 = 0; i2 < this._deepWildcards.length; i2++) {
74410
74387
  if (matcher.matches(this._deepWildcards[i2])) return this._deepWildcards[i2];
74411
74388
  }
@@ -74465,6 +74442,24 @@ var MatcherView = class {
74465
74442
  const current = path8[path8.length - 1];
74466
74443
  return current.values !== void 0 && attrName in current.values;
74467
74444
  }
74445
+ /**
74446
+ * Get the value of a "kept" attribute from the nearest ancestor (or
74447
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
74448
+ * @param {string} attrName
74449
+ * @returns {*}
74450
+ */
74451
+ getAnyParentAttr(attrName) {
74452
+ return this._matcher.getAnyParentAttr(attrName);
74453
+ }
74454
+ /**
74455
+ * Check whether any ancestor (or the current node) kept the given
74456
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
74457
+ * @param {string} attrName
74458
+ * @returns {boolean}
74459
+ */
74460
+ hasAnyParentAttr(attrName) {
74461
+ return this._matcher.hasAnyParentAttr(attrName);
74462
+ }
74468
74463
  /**
74469
74464
  * Get current node's sibling position (child index in parent).
74470
74465
  * @returns {number}
@@ -74543,30 +74538,32 @@ var Matcher = class {
74543
74538
  this.siblingStacks = [];
74544
74539
  this._pathStringCache = null;
74545
74540
  this._view = new MatcherView(this);
74541
+ this._keptAttrs = [];
74546
74542
  }
74547
74543
  /**
74548
74544
  * Push a new tag onto the path.
74549
74545
  * @param {string} tagName
74550
74546
  * @param {Object|null} [attrValues=null]
74551
74547
  * @param {string|null} [namespace=null]
74548
+ * @param {Object|null} [options=null]
74549
+ * @param {string[]} [options.keep] - Names of attributes (from attrValues)
74552
74550
  */
74553
- push(tagName, attrValues = null, namespace = null) {
74551
+ push(tagName, attrValues = null, namespace = null, options = null) {
74554
74552
  this._pathStringCache = null;
74555
74553
  if (this.path.length > 0) {
74556
74554
  this.path[this.path.length - 1].values = void 0;
74557
74555
  }
74558
74556
  const currentLevel = this.path.length;
74559
- if (!this.siblingStacks[currentLevel]) {
74560
- this.siblingStacks[currentLevel] = /* @__PURE__ */ new Map();
74557
+ let level = this.siblingStacks[currentLevel];
74558
+ if (!level) {
74559
+ level = { counts: /* @__PURE__ */ new Map(), total: 0 };
74560
+ this.siblingStacks[currentLevel] = level;
74561
74561
  }
74562
- const siblings = this.siblingStacks[currentLevel];
74563
74562
  const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;
74564
- const counter = siblings.get(siblingKey) || 0;
74565
- let position = 0;
74566
- for (const count of siblings.values()) {
74567
- position += count;
74568
- }
74569
- siblings.set(siblingKey, counter + 1);
74563
+ const counter = level.counts.get(siblingKey) || 0;
74564
+ const position = level.total;
74565
+ level.counts.set(siblingKey, counter + 1);
74566
+ level.total++;
74570
74567
  const node = {
74571
74568
  tag: tagName,
74572
74569
  position,
@@ -74579,6 +74576,16 @@ var Matcher = class {
74579
74576
  node.values = attrValues;
74580
74577
  }
74581
74578
  this.path.push(node);
74579
+ const depth = this.path.length;
74580
+ const keep = options !== null ? options.keep : null;
74581
+ if (keep !== null && keep !== void 0 && keep.length > 0 && attrValues) {
74582
+ for (let i2 = 0; i2 < keep.length; i2++) {
74583
+ const name = keep[i2];
74584
+ if (attrValues[name] !== void 0) {
74585
+ this._keptAttrs.push({ depth, name, value: attrValues[name] });
74586
+ }
74587
+ }
74588
+ }
74582
74589
  }
74583
74590
  /**
74584
74591
  * Pop the last tag from the path.
@@ -74591,6 +74598,10 @@ var Matcher = class {
74591
74598
  if (this.siblingStacks.length > this.path.length + 1) {
74592
74599
  this.siblingStacks.length = this.path.length + 1;
74593
74600
  }
74601
+ const poppedDepth = this.path.length + 1;
74602
+ while (this._keptAttrs.length > 0 && this._keptAttrs[this._keptAttrs.length - 1].depth >= poppedDepth) {
74603
+ this._keptAttrs.pop();
74604
+ }
74594
74605
  return node;
74595
74606
  }
74596
74607
  /**
@@ -74639,6 +74650,36 @@ var Matcher = class {
74639
74650
  const current = this.path[this.path.length - 1];
74640
74651
  return current.values !== void 0 && attrName in current.values;
74641
74652
  }
74653
+ /**
74654
+ * Get the value of a "kept" attribute from the nearest ancestor (or
74655
+ * current node) that declared it via `push(tag, attrs, ns, { keep: [...] })`.
74656
+ * Unlike getAttrValue(), this works regardless of how deep the path has
74657
+ * gone since the attribute was pushed — but only for attribute names that
74658
+ * were explicitly marked with `keep` at push time. Cost is proportional to
74659
+ * the number of currently-kept attributes (typically 0-3), not path depth.
74660
+ * @param {string} attrName
74661
+ * @returns {*} the value, or undefined if no ancestor kept this attribute
74662
+ */
74663
+ getAnyParentAttr(attrName) {
74664
+ const kept = this._keptAttrs;
74665
+ for (let i2 = kept.length - 1; i2 >= 0; i2--) {
74666
+ if (kept[i2].name === attrName) return kept[i2].value;
74667
+ }
74668
+ return void 0;
74669
+ }
74670
+ /**
74671
+ * Check whether any ancestor (or the current node) kept the given
74672
+ * attribute via `push(tag, attrs, ns, { keep: [...] })`.
74673
+ * @param {string} attrName
74674
+ * @returns {boolean}
74675
+ */
74676
+ hasAnyParentAttr(attrName) {
74677
+ const kept = this._keptAttrs;
74678
+ for (let i2 = kept.length - 1; i2 >= 0; i2--) {
74679
+ if (kept[i2].name === attrName) return true;
74680
+ }
74681
+ return false;
74682
+ }
74642
74683
  /**
74643
74684
  * Get current node's sibling position (child index in parent).
74644
74685
  * @returns {number}
@@ -74707,6 +74748,7 @@ var Matcher = class {
74707
74748
  this._pathStringCache = null;
74708
74749
  this.path = [];
74709
74750
  this.siblingStacks = [];
74751
+ this._keptAttrs = [];
74710
74752
  }
74711
74753
  /**
74712
74754
  * Match current path against an Expression.
@@ -74830,7 +74872,8 @@ var Matcher = class {
74830
74872
  snapshot() {
74831
74873
  return {
74832
74874
  path: this.path.map((node) => ({ ...node })),
74833
- siblingStacks: this.siblingStacks.map((map3) => new Map(map3))
74875
+ siblingStacks: this.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level),
74876
+ keptAttrs: this._keptAttrs.map((entry) => ({ ...entry }))
74834
74877
  };
74835
74878
  }
74836
74879
  /**
@@ -74840,7 +74883,8 @@ var Matcher = class {
74840
74883
  restore(snapshot) {
74841
74884
  this._pathStringCache = null;
74842
74885
  this.path = snapshot.path.map((node) => ({ ...node }));
74843
- this.siblingStacks = snapshot.siblingStacks.map((map3) => new Map(map3));
74886
+ this.siblingStacks = snapshot.siblingStacks.map((level) => level ? { counts: new Map(level.counts), total: level.total } : level);
74887
+ this._keptAttrs = (snapshot.keptAttrs || []).map((entry) => ({ ...entry }));
74844
74888
  }
74845
74889
  /**
74846
74890
  * Return the read-only {@link MatcherView} for this matcher.
@@ -89659,180 +89703,6 @@ var runSchema = external_exports.object({
89659
89703
  formatting: formattingSchema.optional()
89660
89704
  });
89661
89705
 
89662
- // ../ooxml/src/queries.ts
89663
- function getBodyElementType(el) {
89664
- const tag = getTagName(el);
89665
- if (tag === "w:p") return "paragraph";
89666
- if (tag === "w:tbl") return "table";
89667
- return "other";
89668
- }
89669
- function extractParagraphText(el) {
89670
- const tag = getTagName(el);
89671
- if (tag !== "w:p") return "";
89672
- const parts = [];
89673
- for (const child of getChildren(el)) {
89674
- const childTag = getTagName(child);
89675
- if (childTag === "w:r") {
89676
- for (const runChild of getChildren(child)) {
89677
- if (getTagName(runChild) === "w:t") {
89678
- parts.push(getTextContent(runChild));
89679
- }
89680
- }
89681
- } else if (childTag === "w:hyperlink") {
89682
- for (const hlChild of getChildren(child)) {
89683
- if (getTagName(hlChild) === "w:r") {
89684
- for (const runChild of getChildren(hlChild)) {
89685
- if (getTagName(runChild) === "w:t") {
89686
- parts.push(getTextContent(runChild));
89687
- }
89688
- }
89689
- }
89690
- }
89691
- }
89692
- }
89693
- return parts.join("");
89694
- }
89695
- function getParagraphTextSegments(el) {
89696
- const segments = [];
89697
- for (const child of getChildren(el)) {
89698
- if (getTagName(child) !== "w:r") continue;
89699
- let pending = [];
89700
- const flush = () => {
89701
- if (pending.length === 0) return;
89702
- const text = pending.map(
89703
- (node) => getChildren(node).reduce(
89704
- (acc, tn) => typeof tn["#text"] === "string" ? acc + tn["#text"] : acc,
89705
- ""
89706
- )
89707
- ).join("");
89708
- segments.push({ element: child, textNodes: pending, text });
89709
- pending = [];
89710
- };
89711
- for (const grandchild of getChildren(child)) {
89712
- if (getTagName(grandchild) === "w:t") {
89713
- pending.push(grandchild);
89714
- continue;
89715
- }
89716
- flush();
89717
- }
89718
- flush();
89719
- }
89720
- return segments;
89721
- }
89722
- function setSegmentText(segment, newText) {
89723
- const children = getChildren(segment.element);
89724
- const textNode = {
89725
- "w:t": [{ "#text": newText }],
89726
- ":@": { "@_xml:space": "preserve" }
89727
- };
89728
- const head = children.indexOf(segment.textNodes[0]);
89729
- children[head] = textNode;
89730
- for (let i2 = segment.textNodes.length - 1; i2 >= 1; i2--) {
89731
- const at2 = children.indexOf(segment.textNodes[i2]);
89732
- if (at2 >= 0) children.splice(at2, 1);
89733
- }
89734
- segment.textNodes = [textNode];
89735
- segment.text = newText;
89736
- }
89737
- function computeReplacementRanges(text, query, replacement, matchType, maxReplacements, startCount) {
89738
- const ranges = [];
89739
- let count = startCount;
89740
- if (matchType === "exact") {
89741
- if (text === query && count < maxReplacements) {
89742
- ranges.push({ start: 0, end: text.length, replacement });
89743
- count++;
89744
- }
89745
- return { ranges, count };
89746
- }
89747
- if (matchType === "regex") {
89748
- const re2 = new RegExp(query, "gi");
89749
- let match2;
89750
- while (count < maxReplacements && (match2 = re2.exec(text)) !== null) {
89751
- ranges.push({ start: match2.index, end: match2.index + match2[0].length, replacement });
89752
- count++;
89753
- if (match2[0].length === 0) re2.lastIndex++;
89754
- }
89755
- return { ranges, count };
89756
- }
89757
- if (query.length === 0) return { ranges, count };
89758
- const lower2 = text.toLowerCase();
89759
- const lowerQuery = query.toLowerCase();
89760
- let searchFrom = 0;
89761
- while (count < maxReplacements) {
89762
- const idx = lower2.indexOf(lowerQuery, searchFrom);
89763
- if (idx === -1) break;
89764
- ranges.push({ start: idx, end: idx + query.length, replacement });
89765
- searchFrom = idx + query.length;
89766
- count++;
89767
- }
89768
- return { ranges, count };
89769
- }
89770
- function applyRangeReplacements(segments, ranges) {
89771
- if (ranges.length === 0) return;
89772
- const bounds = [];
89773
- let offset = 0;
89774
- for (const segment of segments) {
89775
- bounds.push({ segment, start: offset, end: offset + segment.text.length });
89776
- offset += segment.text.length;
89777
- }
89778
- const joined = segments.map((s) => s.text).join("");
89779
- const sorted = [...ranges].sort((a, b) => a.start - b.start);
89780
- for (const { segment, start: segStart, end: segEnd } of bounds) {
89781
- let next = "";
89782
- let cursor = segStart;
89783
- for (const range2 of sorted) {
89784
- if (range2.end <= segStart || range2.start >= segEnd) continue;
89785
- const keepUntil = Math.min(range2.start, segEnd);
89786
- const from = Math.max(cursor, segStart);
89787
- if (keepUntil > from) next += joined.slice(from, keepUntil);
89788
- if (segStart <= range2.start && range2.start < segEnd) next += range2.replacement;
89789
- cursor = Math.max(cursor, range2.end);
89790
- }
89791
- const tail = Math.max(cursor, segStart);
89792
- if (segEnd > tail) next += joined.slice(tail, segEnd);
89793
- if (next !== segment.text) setSegmentText(segment, next);
89794
- }
89795
- }
89796
- function replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade) {
89797
- if (!extractParagraphText(el)) return replacementsMade;
89798
- const segments = getParagraphTextSegments(el);
89799
- if (segments.length === 0) return replacementsMade;
89800
- const text = segments.length === 1 ? segments[0].text : segments.map((s) => s.text).join("");
89801
- const { ranges, count } = computeReplacementRanges(text, query, replacement, matchType, maxReplacements, replacementsMade);
89802
- applyRangeReplacements(segments, ranges);
89803
- return count;
89804
- }
89805
- function replaceText(bodyElements, query, replacement, matchType = "contains", maxReplacements = Infinity) {
89806
- if (matchType === "regex") {
89807
- try {
89808
- new RegExp(query);
89809
- } catch {
89810
- throw new Error(`Invalid regex pattern: ${query}`);
89811
- }
89812
- }
89813
- let replacementsMade = 0;
89814
- for (let i2 = 0; i2 < bodyElements.length && replacementsMade < maxReplacements; i2++) {
89815
- const el = bodyElements[i2];
89816
- const type = getBodyElementType(el);
89817
- if (type === "paragraph") {
89818
- replacementsMade = replaceInParagraph(el, query, replacement, matchType, maxReplacements, replacementsMade);
89819
- } else if (type === "table") {
89820
- for (const child of getChildren(el)) {
89821
- if (getTagName(child) !== "w:tr") continue;
89822
- for (const cell of getChildren(child)) {
89823
- if (getTagName(cell) !== "w:tc") continue;
89824
- for (const p of getChildren(cell)) {
89825
- if (getTagName(p) === "w:p" && replacementsMade < maxReplacements) {
89826
- replacementsMade = replaceInParagraph(p, query, replacement, matchType, maxReplacements, replacementsMade);
89827
- }
89828
- }
89829
- }
89830
- }
89831
- }
89832
- }
89833
- return replacementsMade;
89834
- }
89835
-
89836
89706
  // ../ooxml/src/sections.ts
89837
89707
  var PAGE_SIZES = {
89838
89708
  letter: { w: 12240, h: 15840 },
@@ -90885,6 +90755,9 @@ function parseBlock(el) {
90885
90755
  if (tag === "w:sectPr") return parseBodySectPr(el);
90886
90756
  return parseOpaqueBlock(el);
90887
90757
  }
90758
+ function parseBlockXml(el) {
90759
+ return parseBlock(el);
90760
+ }
90888
90761
  function parseParagraph(el) {
90889
90762
  const properties = [];
90890
90763
  const content = [];
@@ -91102,11 +90975,11 @@ function serializeDocumentXml(doc) {
91102
90975
  function serializeBody(body) {
91103
90976
  const out = [];
91104
90977
  for (const block of body.children) {
91105
- out.push(serializeBlock(block));
90978
+ out.push(serializeBlockXml(block));
91106
90979
  }
91107
90980
  return out;
91108
90981
  }
91109
- function serializeBlock(block) {
90982
+ function serializeBlockXml(block) {
91110
90983
  switch (block.kind) {
91111
90984
  case "paragraph":
91112
90985
  return serializeParagraph(block);
@@ -91356,7 +91229,8 @@ async function docxReplaceText(filePath, rest) {
91356
91229
  const doc = await loadFile2(filePath);
91357
91230
  const { children, count } = replaceEverywhere(doc.body.children, search, replace2);
91358
91231
  if (count === 0) {
91359
- fail2(`No occurrence of ${JSON.stringify(search)} in ${filePath} \u2014 nothing written.`);
91232
+ const why = explainNoMatch(doc.body.children, search);
91233
+ fail2(`No occurrence of ${JSON.stringify(search)} in ${filePath} \u2014 nothing written.${why ? ` ${why}` : ""}`);
91360
91234
  }
91361
91235
  await writeDoc(filePath, replaceChildren(doc, children));
91362
91236
  console.error(`Wrote ${filePath} (${count} replacement${count === 1 ? "" : "s"})`);
@@ -91365,13 +91239,12 @@ function replaceEverywhere(blocks, search, replace2) {
91365
91239
  let count = 0;
91366
91240
  const children = blocks.map((b) => {
91367
91241
  if (b.kind === "paragraph") {
91368
- const [paragraph, n] = replaceInParagraph2(b, search, replace2);
91242
+ const [paragraph, n] = replaceInParagraph(b, search, replace2);
91369
91243
  count += n;
91370
91244
  return paragraph;
91371
91245
  }
91372
91246
  if (b.kind === "opaque_block") {
91373
- const xml = structuredClone(b.xml);
91374
- const n = replaceText([xml], search, replace2, "contains");
91247
+ const [xml, n] = replaceInOpaque(b.xml, search, replace2);
91375
91248
  if (n === 0) return b;
91376
91249
  count += n;
91377
91250
  return { kind: "opaque_block", xml };
@@ -91380,7 +91253,27 @@ function replaceEverywhere(blocks, search, replace2) {
91380
91253
  });
91381
91254
  return { children, count };
91382
91255
  }
91383
- function replaceInParagraph2(p, search, replace2) {
91256
+ function replaceInOpaque(el, search, replace2) {
91257
+ const tag = getTagName(el);
91258
+ if (tag === void 0) return [el, 0];
91259
+ if (tag === "w:p") {
91260
+ const block = parseBlockXml(el);
91261
+ if (block.kind !== "paragraph") return [el, 0];
91262
+ const [paragraph, n] = replaceInParagraph(block, search, replace2);
91263
+ return n === 0 ? [el, 0] : [serializeBlockXml(paragraph), n];
91264
+ }
91265
+ let count = 0;
91266
+ const children = getChildren(el).map((child) => {
91267
+ if (isTextNode(child)) return child;
91268
+ const [next, n] = replaceInOpaque(child, search, replace2);
91269
+ count += n;
91270
+ return next;
91271
+ });
91272
+ if (count === 0) return [el, 0];
91273
+ const attrs = el[":@"];
91274
+ return [{ [tag]: children, ...attrs === void 0 ? {} : { ":@": attrs } }, count];
91275
+ }
91276
+ function replaceInParagraph(p, search, replace2) {
91384
91277
  if (search === "") return [p, 0];
91385
91278
  const rewritten = /* @__PURE__ */ new Map();
91386
91279
  let count = 0;
@@ -91419,6 +91312,71 @@ function replaceInParagraph2(p, search, replace2) {
91419
91312
  });
91420
91313
  return [{ kind: "paragraph", properties: p.properties, content }, count];
91421
91314
  }
91315
+ var ZERO_WIDTH_MARKS = /* @__PURE__ */ new Set([
91316
+ "w:proofErr",
91317
+ "w:footnoteReference",
91318
+ "w:endnoteReference",
91319
+ "w:commentReference",
91320
+ "w:commentRangeStart",
91321
+ "w:commentRangeEnd",
91322
+ "w:annotationRef",
91323
+ "w:bookmarkStart",
91324
+ "w:bookmarkEnd",
91325
+ "w:lastRenderedPageBreak"
91326
+ ]);
91327
+ function interruptsText(node) {
91328
+ const tag = getTagName(node.xml);
91329
+ return tag === void 0 || !ZERO_WIDTH_MARKS.has(tag);
91330
+ }
91331
+ function paragraphText(p) {
91332
+ let out = "";
91333
+ for (const inline of p.content) {
91334
+ if (inline.kind !== "run") continue;
91335
+ for (const child of inline.content) if (child.kind === "text") out += child.value;
91336
+ }
91337
+ return out;
91338
+ }
91339
+ function interruptingTags(p) {
91340
+ const tags = [];
91341
+ for (const inline of p.content) {
91342
+ if (inline.kind !== "run") {
91343
+ if (interruptsText(inline)) tags.push(getTagName(inline.xml) ?? "?");
91344
+ continue;
91345
+ }
91346
+ for (const child of inline.content) {
91347
+ if (child.kind !== "text" && interruptsText(child)) tags.push(getTagName(child.xml) ?? "?");
91348
+ }
91349
+ }
91350
+ return [...new Set(tags)];
91351
+ }
91352
+ function explainNoMatch(blocks, search) {
91353
+ for (const { index, paragraph, nested } of everyParagraph(blocks)) {
91354
+ if (!paragraphText(paragraph).includes(search)) continue;
91355
+ const tags = interruptingTags(paragraph);
91356
+ if (tags.length === 0) continue;
91357
+ const where = nested ? `inside block ${index}` : `at block ${index}`;
91358
+ return `The text IS present ${where}, split by ${tags.join(", ")} \u2014 replace-text will not join across those, because the joined string does not represent them. Search a shorter phrase that does not cross one.`;
91359
+ }
91360
+ return void 0;
91361
+ }
91362
+ function everyParagraph(blocks) {
91363
+ const out = [];
91364
+ const walk2 = (el, index) => {
91365
+ const tag = getTagName(el);
91366
+ if (tag === void 0) return;
91367
+ if (tag === "w:p") {
91368
+ const block = parseBlockXml(el);
91369
+ if (block.kind === "paragraph") out.push({ index, paragraph: block, nested: true });
91370
+ return;
91371
+ }
91372
+ for (const child of getChildren(el)) if (!isTextNode(child)) walk2(child, index);
91373
+ };
91374
+ for (const [index, block] of blocks.entries()) {
91375
+ if (block.kind === "paragraph") out.push({ index, paragraph: block, nested: false });
91376
+ else if (block.kind === "opaque_block") walk2(block.xml, index);
91377
+ }
91378
+ return out;
91379
+ }
91422
91380
  function collectTextSegments(p) {
91423
91381
  const segments = [];
91424
91382
  let current = [];
@@ -91430,12 +91388,12 @@ function collectTextSegments(p) {
91430
91388
  };
91431
91389
  p.content.forEach((inline, inlineIndex) => {
91432
91390
  if (inline.kind !== "run") {
91433
- breakSegment();
91391
+ if (interruptsText(inline)) breakSegment();
91434
91392
  return;
91435
91393
  }
91436
91394
  inline.content.forEach((child, childIndex) => {
91437
91395
  if (child.kind !== "text") {
91438
- breakSegment();
91396
+ if (interruptsText(child)) breakSegment();
91439
91397
  return;
91440
91398
  }
91441
91399
  current.push({
@@ -91494,7 +91452,10 @@ function applyBatchOp(doc, op, index) {
91494
91452
  }
91495
91453
  case "replace-text": {
91496
91454
  const { children, count } = replaceEverywhere(doc.body.children, op.search, op.replace);
91497
- if (count === 0) fail2(`[op ${index}] No occurrence of ${JSON.stringify(op.search)} \u2014 batch aborted.`);
91455
+ if (count === 0) {
91456
+ const why = explainNoMatch(doc.body.children, op.search);
91457
+ fail2(`[op ${index}] No occurrence of ${JSON.stringify(op.search)} \u2014 batch aborted.${why ? ` ${why}` : ""}`);
91458
+ }
91498
91459
  return replaceChildren(doc, children);
91499
91460
  }
91500
91461
  default: {
@@ -91520,7 +91481,13 @@ Uses Lotics' own OOXML engine; round-trips faithfully with the Lotics editor and
91520
91481
  lotics docx batch <file> '<json-array-of-ops>' Apply many ops in one parse/serialize cycle
91521
91482
 
91522
91483
  Edit ops mutate the file atomically (temp file + rename). Structure inside opaque blocks (tables, custom XML) is
91523
- preserved verbatim; replace-text rewrites the text within them.`);
91484
+ preserved verbatim; replace-text rewrites the text within them.
91485
+
91486
+ replace-text matches across run boundaries (Word splits a run at every formatting change) and reads through marks
91487
+ that take no place in the sentence \u2014 spell-check markers, footnote/endnote/comment refs, bookmarks. It will NOT
91488
+ join across something that occupies space in the text (a line break, tab, symbol, drawing, or any other tag),
91489
+ because the joined string does not represent it. The same rule applies inside a table cell as outside it. When a
91490
+ search fails but the words ARE on the page, the error names the block and the mark that split them.`);
91524
91491
  }
91525
91492
  async function runDocxCommand(subcommand, toolArgs, restArgs) {
91526
91493
  switch (subcommand) {
@@ -91984,10 +91951,6 @@ COMMANDS
91984
91951
  lotics knowledge update <id> [--from <file.md> | --content <str>] [--name <n>] [--description <d>]
91985
91952
  Update a doc \u2014 sends only the fields you pass
91986
91953
  lotics knowledge rm <id> Archive a doc
91987
- lotics ui link <component> [--ui-src <path>] [--remove]
91988
- Dev-link @lotics/ui to packages/ui/src (Vite alias
91989
- + tsc paths) for live HMR + typecheck. Monorepo apps
91990
- auto-find it; external apps pass --ui-src / LOTICS_UI_SRC
91991
91954
  lotics xlsx <subcommand> ... Read/write/edit .xlsx files on your local filesystem
91992
91955
  (uses the bundled Lotics xlsx engine; prefer over
91993
91956
  npm xlsx/exceljs for round-trip fidelity)
@@ -92406,22 +92369,6 @@ async function main() {
92406
92369
  await runPreviewCommand(subcommand, flags);
92407
92370
  return;
92408
92371
  }
92409
- if (command === "ui") {
92410
- if (subcommand === "link") {
92411
- const component = toolArgs;
92412
- if (!component) {
92413
- console.error("Usage: lotics ui link <component> [--ui-src <abs path>] [--remove]");
92414
- console.error("Dev-links @lotics/ui to packages/ui/src (Vite + tsc) for live HMR + typecheck.");
92415
- console.error("Monorepo apps find packages/ui/src automatically; external apps pass --ui-src / LOTICS_UI_SRC.");
92416
- process.exit(1);
92417
- }
92418
- appUiLink({ component, uiSrc: flags.uiSrc, remove: restArgs.includes("--remove") });
92419
- return;
92420
- }
92421
- console.error(`Unknown ui subcommand: ${subcommand ?? "(none)"}`);
92422
- console.error("Usage: lotics ui link <component> [--ui-src <abs path>] [--remove]");
92423
- process.exit(1);
92424
- }
92425
92372
  if (command === "app" && subcommand === "workflow" && toolArgs === "check") {
92426
92373
  await appWorkflowCheck({ alias: restArgs[0] });
92427
92374
  return;
@@ -43,8 +43,8 @@ Per-command syntax, flags, contracts, and gotchas for the public `lotics` CLI. S
43
43
  | `lotics app subdomain <new-subdomain>` | Rename the app's public `<slug>.lotics.app` address via `PUT /v1/apps/{id}/subdomain`. app_id comes from the local `package.json` manifest; the chosen slug must be a valid DNS label and free; the old address stops resolving. |
44
44
  | `lotics app rename "<new name>"` | Change the app's display name (launcher/title) via the `update_app` tool. app_id comes from the local `package.json` manifest; the public address (`subdomain`) and code (`deploy`) are unchanged. |
45
45
  | `lotics app dev [path] [--port=N] [--vite-port=N] [--view-as=<member_id>]` | Spawn Vite dev server + an RPC-forwarding HTTP server. The wrapper page embeds the iframe with `sandbox="allow-scripts allow-same-origin"` matching production; postMessage ops (query / workflow / members / context / upload / openExternal / urlState / agentRun) are forwarded to api.lotics.ai using the CLI's API key — file bytes move in **both** directions through the dev server's own relays, never browser↔storage (the former GAP-44): dev runs against the PROD bucket, whose CORS admits `https://*.lotics.app` and not `http://localhost:<port>`, so a direct browser transfer is blocked — no upload could complete and no preview engine (PDF/Word/Excel all FETCH the bytes) could read a file. `upload` mints a presigned URL and PUTs it **to `PUT /_upload/<file_id>`** (`dev/upload_relay.ts`) from the wrapper page — same-origin, so no preflight and no CORS — and Node forwards it on; every presigned `url`/`thumbnail_url`/`preview_url` on a **file object** in an RPC result is rewritten to **`GET /_file/<token>`** (`dev/file_relay.ts`, absolute — the iframe would resolve a relative path against Vite), which streams the bytes back with `Range` passthrough (206s intact, so PDF seeking works) and an `Access-Control-Allow-Origin` for the Vite origin (the one cross-origin hop left is OUR response to allow). Neither relay ever takes a destination from the client — it gets a `file_id`/token and transfers only to/from a URL it minted or observed itself, so there is no client-controlled target and no SSRF surface. A URL in a record's own text cell is NOT rewritten. Production is unchanged (direct-to-storage, no bytes through the API server); `openExternal` and `urlState.get/set` are handled locally (the latter read/write the wrapper page's own address bar — `set` writes in place via `replaceState` and browser back/forward broadcast a `url-state` message back, so `useUrlState` survives refresh and is shareable in the dev loop; in-app *routing* is the app's own (the iframe owns its url via `@lotics/app-sdk/router`), and the wrapper bakes the saved screen (`_loc`) into the iframe src on load so a refresh restores it, mirroring production); `agentRun` (streaming) is proxied through `POST /_agent_run`, which opens the run's SSE with the CLI key and pipes chunks back to the iframe (`stream-chunk`* → `stream-end`), so `useAgentRun` works in the dev loop just like production; `context` resolves the viewer (`member_id` from `cli/whoami` + `comments_enabled` from the local manifest) and fetches the installation's stored `config` live from the app row, so `useConfig()` renders the same values as production. `--view-as` (global flag; also `LOTICS_VIEW_AS`) threads `x-view-as-member-id` so `is_current_member` + `context` resolve to that member — **admin key only** (the server 403s a non-admin), writes stay attributed to the key owner. Hot reload via Vite; full DevTools / Playwright access via plain localhost. The dev-optimizer pre-bundle list (`optimizeDeps.include`, load-bearing for dev) is imported from `@lotics/ui/vite` (`loticsOptimizeDeps`) rather than hardcoded in the scaffold, so it tracks the installed `@lotics/ui` and can never go stale. Binds **loopback only** (`127.0.0.1`) — `/_rpc` dispatches with the developer's API key, so a socket on every interface would hand anyone on the network full read/write on the workspace. |
46
- | `lotics ui link <component> [--ui-src <path>] [--remove]` | Dev-link `@lotics/ui` to `packages/ui/src` by inserting (or removing) a package-wide `{ find: /^@lotics\/ui\/(.+)$/, replacement: "<absUiSrc>/$1" }` alias in the app's `vite.config.ts` resolve.alias — so edits to `packages/ui/src` go live (HMR) and bundle on deploy, without a publish round-trip. **`packages/ui/src` resolution:** walk up for a monorepo checkout, else the explicit `--ui-src <abs path>` / `LOTICS_UI_SRC` env — that's how an **EXTERNAL app** (one that consumes `@lotics/ui` from npm, e.g. under `~/lotics_apps`) links the local kit; fails loud when neither resolves, or when `--ui-src` isn't a directory. No auth (local file edit). Idempotent. `component` is advisory/validation only (the alias covers every subpath). **Vite-only, by design:** the app's `tsc` still resolves `@lotics/ui` from `node_modules` (the published `.d.ts`) — the kit `src` can't be typechecked inside an app because it's RN-Web (uses `react-native-web` types the app resolves as base `react-native`), so typecheck the kit in `packages/ui` and let the finalize publish restore the app's own typecheck. Reminds to restart dev + `rm node_modules/.vite`, and to finalize (`--remove` + publish-chain bump). |
46
+ | `LOTICS_UI_SRC=<abs path to packages/ui/src>` (env, not a command) | Dev-link `@lotics/ui` to a monorepo checkout for the length of ONE command: the app's own `vite.config.ts` reads the variable and adds a `{ find: /^@lotics\/ui\/(.+)$/, replacement: "<LOTICS_UI_SRC>/$1" }` entry to `resolve.alias`, so kit edits go live under `lotics app dev` (HMR) and bundle under `lotics app deploy`. Unset ⇒ the kit resolves from `node_modules` as normal. **Nothing is written to disk** — there is no link/unlink step, nothing to leave switched on, and no config for the CLI to corrupt (the `lotics ui link` command this replaces edited `vite.config.ts` by regex and twice deleted the load-bearing `react-native` → `react-native-web` alias with the array's closing bracket, breaking the app's build entirely — GAP-133/142). Identical for a monorepo app and an EXTERNAL one (e.g. `~/lotics_apps`). `app dev` **warns** when the variable is set but the app's `vite.config.ts` predates it (scaffolded earlier) and prints the lines to add; `app deploy` **warns** that the bundle carries kit code from your working copy rather than the published package. **Vite-only, by design:** the app's `tsc` still resolves `@lotics/ui` from `node_modules` (the published `.d.ts`) — the kit `src` can't be typechecked inside an app because it's RN-Web, so typecheck the kit in `packages/ui` and let the finalize publish restore the app's own typecheck. |
47
47
  | `lotics xlsx <subcmd>` | Local .xlsx read/write/edit using the bundled `@lotics/xlsx` engine (no auth, no network). 14 named subcommands (read, write, set-cell, clear-range, merge, unmerge, add-sheet, delete-sheet, rename-sheet, insert-rows, delete-rows, insert-cols, delete-cols, set-style) + `batch` for applying multiple of the same 14 ops in a single parse/export cycle. `read` also takes `--sheet <name>` (limit output to one sheet — unknown name fails with the available list) and `--range <sheet>!<A1:G60>` (limit to a cell window; the `<sheet>!` prefix is optional when `--sheet` supplies the sheet, a single cell like `S1!B2` is a 1×1 window) to trim a large workbook's JSON — the output shape is unchanged, only the `sheets` array and each sheet's `cells` map are filtered. Atomic in-place write (temp file + rename). |
48
- | `lotics docx <subcmd>` | Local .docx read/write/edit using the bundled `@lotics/docx` engine (OOXML round-trip surface only — no ProseMirror baggage). Subcommands: read, write, append-paragraph, insert-paragraph, delete-block, replace-text, batch. A legacy `.doc` (Word 97–2003 OLE2 binary) is detected in `loadFile` and routed through `@lotics/ooxml`'s `loadDocxFromBuffer` (which re-emits it as real OOXML) before reading — so `lotics docx read` works on a `.doc`, not just a `.docx`. Opaque blocks (tables, custom XML) preserved verbatim. Atomic in-place write. |
48
+ | `lotics docx <subcmd>` | Local .docx read/write/edit using the bundled `@lotics/docx` engine (OOXML round-trip surface only — no ProseMirror baggage). Subcommands: read, write, append-paragraph, insert-paragraph, delete-block, replace-text, batch. A legacy `.doc` (Word 97–2003 OLE2 binary) is detected in `loadFile` and routed through `@lotics/ooxml`'s `loadDocxFromBuffer` (which re-emits it as real OOXML) before reading — so `lotics docx read` works on a `.doc`, not just a `.docx`. Opaque blocks (tables, custom XML) preserved verbatim. Atomic in-place write. **`replace-text` matches across run boundaries** — Word splits a run at every formatting change, so a `{{marker}}` routinely lands split — and reads straight THROUGH marks that occupy no place in the sentence (`w:proofErr`, `w:footnoteReference`, endnote/comment refs + ranges, `w:bookmarkStart`/`End`, `w:lastRenderedPageBreak`). `w:proofErr` is the one that decides whether this works in practice — Word brackets every word its dictionary rejects, so on non-English text it lands between nearly every pair of runs. It still refuses to join across anything that occupies space in the text — `w:br`, `w:tab`, `w:sym`, a drawing, or any tag not on that allowlist — because the joined string does not represent the glyph and a match there would rewrite text the caller never saw. The SAME rule applies inside a table cell as outside it — both run one `replaceInParagraph` over paragraphs found at any depth, so a marker split by a line break is refused in both rather than rewritten in the cell and skipped in the body under a success message. Zero matches is always a hard error, never a silent no-op, and when the words ARE on the page the error names the block and the splitting mark (`The text IS present at block 1, split by w:br …`) rather than claiming the text is absent. |
49
49
  | `lotics file preview <file\|fil_id> [-o out.png]` | (also `lotics preview`) Render a .docx/.xlsx to a PNG using the SAME engines the frontend FilePreview uses (`@lotics/docx` `loadDocxIntoElement` / `@lotics/xlsx` `drawSpreadsheet`) — so what you see matches an operator. Accepts a **local path** OR a stored **`fil_…` id** (`isStoredFileId` — a bare id, no extension): an id is first downloaded to a temp dir via `downloadFileById` (the `signed_url` presign path — same authority as `lotics file download`), rendered, then the transient source is removed; with no `-o` the PNG lands in cwd under the stored file's base name (`defaultPreviewOutputPath`). Drives a headless Chrome over **CDP with only Node built-ins** (`WebSocket`/`fetch`/`http`/`child_process`) — zero npm deps, the CLI stays a single bundled binary. The browser render logic is a separate esbuild **browser** bundle shipped at `dist/render_page.js` (built by `build_cli.mjs`, excluded from the node `tsgo`), served over a throwaway localhost http server and screenshotted full-page. **Requires a Chrome/Chromium on the machine** — detected from `CHROME_PATH`/`LOTICS_CHROME`, then Playwright's installed chromium, then system paths — inherent to rendering these browser formats; a clear "install a browser" error otherwise. PDFs need no render (open them directly). |
50
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lotics/cli",
3
- "version": "0.102.0",
3
+ "version": "0.103.0",
4
4
  "description": "Lotics SDK and CLI for AI agents",
5
5
  "type": "module",
6
6
  "bin": {