@lobu/runtime-device 20.2.0 → 21.0.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.
Files changed (107) hide show
  1. package/dist/component.json +1 -1
  2. package/dist/dependencies.bun.lock +42 -36
  3. package/npm-shrinkwrap.json +270 -224
  4. package/package.json +1 -1
  5. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.d.ts +7 -2
  6. package/vendor/cli/dist/commands/_lib/apply/apply-cmd.js +77 -75
  7. package/vendor/cli/dist/commands/_lib/apply/client.d.ts +40 -25
  8. package/vendor/cli/dist/commands/_lib/apply/client.js +31 -39
  9. package/vendor/cli/dist/commands/_lib/apply/deployment.d.ts +1 -1
  10. package/vendor/cli/dist/commands/_lib/apply/deployment.js +2 -2
  11. package/vendor/cli/dist/commands/_lib/apply/desired-state.d.ts +47 -11
  12. package/vendor/cli/dist/commands/_lib/apply/desired-state.js +106 -7
  13. package/vendor/cli/dist/commands/_lib/apply/diff.d.ts +14 -6
  14. package/vendor/cli/dist/commands/_lib/apply/diff.js +42 -23
  15. package/vendor/cli/dist/commands/_lib/apply/map-config.js +2 -3
  16. package/vendor/cli/dist/commands/_lib/apply/render.js +2 -0
  17. package/vendor/cli/dist/commands/_lib/apply/rollback-cmd.js +3 -3
  18. package/vendor/cli/dist/commands/_lib/connector-loader.d.ts +5 -1
  19. package/vendor/cli/dist/commands/_lib/connector-loader.js +1 -1
  20. package/vendor/cli/dist/commands/_lib/ensure-deps-installed.d.ts +15 -26
  21. package/vendor/cli/dist/commands/_lib/ensure-deps-installed.js +227 -136
  22. package/vendor/cli/dist/commands/_lib/view-bundler.d.ts +33 -0
  23. package/vendor/cli/dist/commands/_lib/view-bundler.js +207 -0
  24. package/vendor/cli/dist/commands/_lib/view-reapply.d.ts +60 -0
  25. package/vendor/cli/dist/commands/_lib/view-reapply.js +182 -0
  26. package/vendor/cli/dist/commands/dev.d.ts +14 -5
  27. package/vendor/cli/dist/commands/dev.js +56 -8
  28. package/vendor/cli/dist/commands/init.d.ts +1 -1
  29. package/vendor/cli/dist/commands/init.js +4 -4
  30. package/vendor/cli/dist/config/define.d.ts +25 -8
  31. package/vendor/cli/dist/config/define.js +24 -0
  32. package/vendor/cli/dist/connectors/README.md +15 -16
  33. package/vendor/cli/dist/connectors/github.ts +15 -9
  34. package/vendor/cli/dist/connectors/google_calendar.ts +21 -31
  35. package/vendor/cli/dist/connectors/google_drive.ts +106 -131
  36. package/vendor/cli/dist/connectors/google_gmail.ts +53 -30
  37. package/vendor/cli/dist/connectors/hackernews.ts +2 -5
  38. package/vendor/cli/dist/connectors/jira.ts +62 -27
  39. package/vendor/cli/dist/connectors/linear.ts +55 -21
  40. package/vendor/cli/dist/connectors/microsoft_outlook.ts +151 -110
  41. package/vendor/cli/dist/connectors/postgres.ts +19 -11
  42. package/vendor/cli/dist/connectors/producthunt.ts +8 -6
  43. package/vendor/cli/dist/connectors/reddit.ts +2 -2
  44. package/vendor/cli/dist/connectors/rss.ts +2 -2
  45. package/vendor/cli/dist/connectors/whatsapp_web.ts +5 -4
  46. package/vendor/cli/dist/connectors/x.ts +32 -17
  47. package/vendor/cli/dist/connectors/youtube.ts +18 -5
  48. package/vendor/cli/dist/internal/connector-compiler.d.ts +1 -1
  49. package/vendor/cli/dist/internal/connector-compiler.js +216 -17
  50. package/vendor/cli/dist/runtime-components.json +4 -4
  51. package/vendor/cli/package.json +2 -1
  52. package/vendor/connector-sdk/dist/connector-runtime.d.ts +4 -6
  53. package/vendor/connector-sdk/dist/connector-runtime.js +3 -5
  54. package/vendor/connector-sdk/dist/connector-types.d.ts +28 -13
  55. package/vendor/connector-sdk/dist/define-connector.d.ts +4 -1
  56. package/vendor/connector-sdk/dist/define-connector.js +4 -1
  57. package/vendor/connector-sdk/dist/http-client.d.ts +18 -7
  58. package/vendor/connector-sdk/dist/http-client.js +15 -13
  59. package/vendor/connector-sdk/dist/index.d.ts +1 -1
  60. package/vendor/connector-sdk/dist/retry.d.ts +15 -3
  61. package/vendor/connector-sdk/dist/retry.js +40 -64
  62. package/vendor/connector-sdk/package.json +1 -1
  63. package/vendor/connector-worker/dist/agent-turn/guest-entry.js +122 -10
  64. package/vendor/connector-worker/dist/agent-turn/guest.bundle.js +78 -10
  65. package/vendor/connector-worker/dist/agent-turn/types.d.ts +34 -4
  66. package/vendor/connector-worker/dist/compile/index.d.ts +21 -2
  67. package/vendor/connector-worker/dist/compile/index.js +41 -8
  68. package/vendor/connector-worker/dist/compile/source-capture.d.ts +10 -0
  69. package/vendor/connector-worker/dist/compile/source-capture.js +108 -0
  70. package/vendor/connector-worker/dist/daemon/agent-turn.js +97 -10
  71. package/vendor/connector-worker/dist/daemon/automation.d.ts +1 -1
  72. package/vendor/connector-worker/dist/daemon/executor.d.ts +0 -1
  73. package/vendor/connector-worker/dist/daemon/executor.js +42 -51
  74. package/vendor/connector-worker/dist/daemon/start.js +5 -1
  75. package/vendor/connector-worker/dist/executor/interface.d.ts +12 -8
  76. package/vendor/connector-worker/dist/executor/isolate.js +45 -28
  77. package/vendor/connector-worker/dist/self-check/index.js +15 -13
  78. package/vendor/connector-worker/package.json +1 -1
  79. package/vendor/core/dist/agent-policy.js +3 -0
  80. package/vendor/core/dist/connector-query-errors.d.ts +3 -3
  81. package/vendor/core/dist/connector-query-errors.js +8 -3
  82. package/vendor/core/dist/contracts/tools/manage-connections.d.ts +24 -0
  83. package/vendor/core/dist/contracts/tools/manage-connections.js +13 -0
  84. package/vendor/core/dist/contracts/tools/manage-entity-schema.d.ts +15 -25
  85. package/vendor/core/dist/contracts/tools/manage-entity-schema.js +3 -5
  86. package/vendor/core/dist/contracts/tools/manage-feeds.d.ts +11 -0
  87. package/vendor/core/dist/contracts/tools/manage-feeds.js +12 -1
  88. package/vendor/core/dist/contracts/tools/manage-operations.d.ts +47 -6
  89. package/vendor/core/dist/contracts/tools/manage-operations.js +36 -1
  90. package/vendor/core/dist/contracts/tools/manage-views.d.ts +293 -0
  91. package/vendor/core/dist/contracts/tools/manage-views.js +203 -0
  92. package/vendor/core/dist/contracts/tools/source-files-schema.d.ts +7 -0
  93. package/vendor/core/dist/contracts/tools/source-files-schema.js +19 -0
  94. package/vendor/core/dist/contracts/tools/source-files.d.ts +14 -0
  95. package/vendor/core/dist/contracts/tools/source-files.js +55 -0
  96. package/vendor/core/dist/contracts/tools/view-content-hash.d.ts +37 -0
  97. package/vendor/core/dist/contracts/tools/view-content-hash.js +58 -0
  98. package/vendor/core/dist/contracts/tools/view-path.d.ts +18 -0
  99. package/vendor/core/dist/contracts/tools/view-path.js +24 -0
  100. package/vendor/core/dist/contracts/worker/protocol.d.ts +73 -8
  101. package/vendor/core/dist/contracts/worker/protocol.js +58 -9
  102. package/vendor/core/dist/reserved.d.ts +3 -3
  103. package/vendor/core/dist/reserved.js +9 -1
  104. package/vendor/core/dist/utils/secret-redaction.js +2 -0
  105. package/vendor/core/package.json +25 -5
  106. package/vendor/core/dist/contracts/tools/manage-view-templates.d.ts +0 -165
  107. package/vendor/core/dist/contracts/tools/manage-view-templates.js +0 -130
@@ -1,153 +1,244 @@
1
- /**
2
- * Ensure a connector project's npm dependencies are installed before the CLI
3
- * compiles its connectors. esbuild bundles a connector's imports relative to
4
- * the connector file's directory, so the project's own `node_modules` (next to
5
- * `package.json`) must exist. We install when stale, preferring `bun` (faster,
6
- * if the user has it) and falling back to `npm` (always present with Node) so
7
- * the lobu CLI never forces a bun install on the user's machine.
8
- * `--ignore-scripts` keeps install-time supply-chain surface off the user's
9
- * machine — packages that need build scripts (native bindings) belong in
10
- * `runtime.nix.packages`, not bundled npm.
11
- */
12
- import { execFileSync } from "node:child_process";
13
- import { existsSync, statSync } from "node:fs";
14
- import { delimiter, dirname, join } from "node:path";
15
- // Per-process memo so `lobu apply` installs each project root at most once.
16
- const ensuredRoots = new Set();
17
- /**
18
- * Find the connector's project root — the nearest ancestor with
19
- * `lobu.config.ts`. Anchoring on `lobu.config.ts` (not any ancestor
20
- * `package.json`) is what stops a connector inside a monorepo from resolving to
21
- * the monorepo's root package.json and triggering a wrong-directory install.
22
- */
23
- function findProjectRoot(fromFile) {
24
- let dir = dirname(fromFile);
25
- for (let i = 0; i < 40; i++) {
26
- if (existsSync(join(dir, "lobu.config.ts")))
27
- return dir;
28
- const parent = dirname(dir);
29
- if (parent === dir)
30
- break;
31
- dir = parent;
32
- }
33
- return null;
1
+ /** Project dependencies are created by init, and frozen before apply compiles. */
2
+ import { execFile } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
+ import { delimiter, dirname, join, relative, resolve } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import lockfile from "proper-lockfile";
8
+ import { globSync } from "tinyglobby";
9
+ const exec = promisify(execFile);
10
+ const LOCKS = [
11
+ "bun.lock",
12
+ "bun.lockb",
13
+ "package-lock.json",
14
+ "npm-shrinkwrap.json",
15
+ "pnpm-lock.yaml",
16
+ "yarn.lock",
17
+ ];
18
+ function manifestAt(root) {
19
+ return JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
34
20
  }
35
- /**
36
- * The project is "stale" if `node_modules` is missing or its mtime is older
37
- * than whichever lockfile the project uses (`bun.lock` for a bun-based project,
38
- * `package-lock.json` for an npm-based one). Honouring both means switching
39
- * installers between runs doesn't trigger spurious reinstalls.
40
- */
41
- function installIsStale(root) {
42
- const nodeModules = join(root, "node_modules");
43
- if (!existsSync(nodeModules))
44
- return true;
45
- for (const lockName of ["bun.lock", "package-lock.json"]) {
46
- const lock = join(root, lockName);
47
- if (!existsSync(lock))
48
- continue;
49
- try {
50
- if (statSync(lock).mtimeMs > statSync(nodeModules).mtimeMs)
51
- return true;
52
- }
53
- catch {
54
- // unreadable lockfile — treat as fresh rather than reinstall on every run
55
- }
21
+ function workspacePackages(root, manifest) {
22
+ const patterns = Array.isArray(manifest.workspaces)
23
+ ? manifest.workspaces
24
+ : manifest.workspaces?.packages;
25
+ if (!patterns)
26
+ return [];
27
+ if (!Array.isArray(patterns) ||
28
+ patterns.some((p) => typeof p !== "string" ||
29
+ p.startsWith("/") ||
30
+ p.split("/").includes(".."))) {
31
+ throw new Error(`Invalid workspace paths in ${join(root, "package.json")}. Keep workspace packages under their root.`);
56
32
  }
57
- return false;
33
+ return globSync(patterns.map((p) => `${p.replace(/\/$/, "")}/package.json`), {
34
+ cwd: root,
35
+ absolute: true,
36
+ ignore: ["**/node_modules/**", "**/.git/**"],
37
+ followSymbolicLinks: false,
38
+ })
39
+ .map((p) => dirname(p))
40
+ .sort();
58
41
  }
59
- function hasOnPath(bin) {
60
- const cmd = commandOnPath(bin);
61
- if (!cmd)
62
- return false;
63
- try {
64
- // `env: process.env` is node's default; passed explicitly because bun
65
- // otherwise resolves the binary against the STARTUP environment's PATH,
66
- // ignoring runtime changes (which the tests rely on to stage fakes).
67
- execFileSync(cmd, ["--version"], { stdio: "ignore", env: process.env });
68
- return true;
69
- }
70
- catch {
71
- return false;
42
+ function findProject(cwd) {
43
+ // A directory without lobu.config.ts is not a Lobu project: never install into it.
44
+ if (!existsSync(join(cwd, "lobu.config.ts")))
45
+ return null;
46
+ const projectDir = realpathSync(cwd);
47
+ if (!existsSync(join(projectDir, "package.json")))
48
+ return null;
49
+ let root = projectDir;
50
+ // Only a declared workspace member inherits an ancestor's lockfile.
51
+ for (let dir = dirname(projectDir);; dir = dirname(dir)) {
52
+ if (existsSync(join(dir, "package.json"))) {
53
+ // An unrelated ancestor is not part of this project's dependency inputs.
54
+ // Validate the selected root below; malformed unrelated manifests cannot own it.
55
+ try {
56
+ if (workspacePackages(dir, manifestAt(dir)).includes(root))
57
+ root = dir;
58
+ }
59
+ catch {
60
+ // No valid workspace declaration establishes ownership at this ancestor.
61
+ }
62
+ }
63
+ if (dirname(dir) === dir)
64
+ break;
72
65
  }
66
+ const manifest = manifestAt(root);
67
+ return {
68
+ root,
69
+ manifest,
70
+ packages: [root, ...workspacePackages(root, manifest)],
71
+ };
73
72
  }
74
73
  function commandOnPath(bin) {
75
- const path = process.env.PATH;
76
- if (!path)
77
- return null;
78
- for (const dir of path.split(delimiter)) {
79
- if (!dir)
80
- continue;
81
- const candidate = join(dir, bin);
82
- if (existsSync(candidate))
83
- return candidate;
74
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
75
+ if (dir && existsSync(join(dir, bin)))
76
+ return resolve(dir, bin);
84
77
  }
85
78
  return null;
86
79
  }
87
- const bunInstaller = { cmd: "bun", args: ["install", "--ignore-scripts"] };
88
- const npmInstaller = {
89
- cmd: "npm",
90
- args: ["install", "--ignore-scripts", "--no-audit", "--no-fund"],
91
- };
92
- /**
93
- * Pick an installer for the user's project. Honour an existing lockfile so we
94
- * don't mix `bun.lock` and `package-lock.json` for the same project, then fall
95
- * back to whatever's available — bun is faster when present, npm is always
96
- * available because Node ships it. The lobu CLI never requires bun on the
97
- * user's machine.
98
- */
99
- function pickInstaller(root) {
100
- const hasNpmLock = existsSync(join(root, "package-lock.json"));
101
- if (hasNpmLock)
102
- return npmInstaller;
103
- const hasBunLock = existsSync(join(root, "bun.lock"));
104
- const bunAvailable = hasOnPath("bun");
105
- if (hasBunLock && bunAvailable)
106
- return bunInstaller;
107
- if (bunAvailable)
108
- return bunInstaller;
109
- return npmInstaller;
80
+ function policy(project, mode) {
81
+ const { root, manifest } = project;
82
+ const locks = LOCKS.filter((name) => existsSync(join(root, name)));
83
+ if (locks.length > 1)
84
+ throw new Error(`Conflicting lockfiles in ${root}: ${locks.join(", ")}. Keep the lockfile for your declared package manager.`);
85
+ const lock = locks[0];
86
+ if (lock === "pnpm-lock.yaml" || lock === "yarn.lock")
87
+ throw new Error(`Lobu project installation supports Bun and npm; ${lock} requires a different package manager.`);
88
+ const declaration = manifest.packageManager;
89
+ const parsed = declaration?.match(/^(bun|npm)@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+sha(?:224|256|384|512)\.[a-fA-F0-9]+)?$/);
90
+ if (declaration && !parsed)
91
+ throw new Error(`Unsupported packageManager ${JSON.stringify(declaration)}. Declare an exact bun@version or npm@version.`);
92
+ const lockedManager = lock
93
+ ? lock.startsWith("bun.")
94
+ ? "bun"
95
+ : "npm"
96
+ : undefined;
97
+ const manager = parsed?.[1] ?? lockedManager ?? (commandOnPath("bun") ? "bun" : "npm");
98
+ if (lockedManager && lockedManager !== manager)
99
+ throw new Error(`packageManager ${declaration} conflicts with ${lock}. Use one package manager and its lockfile.`);
100
+ for (const member of project.packages.slice(1)) {
101
+ const nested = manifestAt(member).packageManager;
102
+ if (nested && nested !== declaration)
103
+ throw new Error(`Workspace package ${member} declares a different packageManager. Declare the manager at ${root}.`);
104
+ if (LOCKS.some((name) => existsSync(join(member, name))))
105
+ throw new Error(`Workspace package ${member} has its own lockfile. Use the workspace lockfile in ${root}.`);
106
+ }
107
+ if (!lock && mode === "frozen")
108
+ throw new Error(`Missing lockfile in ${root}. Run '${manager} install --ignore-scripts' there and commit the lockfile before applying.`);
109
+ return { manager, lock, version: parsed?.[2] };
110
110
  }
111
- /**
112
- * Run the project's dependency install in `root` with the picked installer
113
- * (bun if available, else npm; `--ignore-scripts` always). Throws when the
114
- * install fails or the installer binary is missing — callers decide whether
115
- * that's fatal (`lobu apply` compile path) or a warning (`lobu init`).
116
- */
117
- export function installProjectDeps(root, opts = {}) {
118
- const installer = pickInstaller(root);
119
- const cmd = commandOnPath(installer.cmd);
120
- if (!cmd) {
121
- throw new Error(`Installer not found on PATH: ${installer.cmd}`);
111
+ function fingerprint(project) {
112
+ const hash = createHash("sha256");
113
+ for (const dir of project.packages) {
114
+ for (const name of ["package.json", ".npmrc", "bunfig.toml", ...LOCKS]) {
115
+ const file = join(dir, name);
116
+ hash.update(relative(project.root, file));
117
+ hash.update(existsSync(file) ? readFileSync(file) : "<missing>");
118
+ hash.update("\0");
119
+ }
122
120
  }
123
- // `env: process.env` — see hasOnPath for why it's passed explicitly.
124
- execFileSync(cmd, installer.args, {
125
- cwd: root,
126
- stdio: opts.stdio ?? "inherit",
127
- env: process.env,
128
- });
129
- return { installer: installer.cmd };
121
+ return hash.digest("hex");
130
122
  }
131
- /**
132
- * Install the connector project's deps if missing/stale. No-op when the
133
- * connector has no `package.json` (no declared npm deps to bundle).
134
- */
135
- export function ensureProjectDepsInstalled(connectorFilePath, log) {
136
- const root = findProjectRoot(connectorFilePath);
137
- if (!root || ensuredRoots.has(root))
138
- return;
139
- // No package.json at the project root → the connector declares no npm deps
140
- // (the SDK is runtime-provided/externalized), so there's nothing to install.
141
- if (!existsSync(join(root, "package.json"))) {
142
- ensuredRoots.add(root);
143
- return;
123
+ function missingDependency(project, readOnly = false) {
124
+ for (const dir of project.packages) {
125
+ const manifest = manifestAt(dir);
126
+ for (const name of Object.keys({
127
+ ...manifest.dependencies,
128
+ ...manifest.devDependencies,
129
+ })) {
130
+ // Optional declarations override required entries and may be omitted by the installer.
131
+ if (Object.hasOwn(manifest.optionalDependencies ?? {}, name))
132
+ continue;
133
+ // Config loading aliases these two packages to the running CLI's SDK.
134
+ // Preserve zero-install validation without hiding missing user libraries.
135
+ if (readOnly && (name === "@lobu/cli" || name === "@lobu/connector-sdk"))
136
+ continue;
137
+ let at = dir;
138
+ while (!existsSync(join(at, "node_modules", name, "package.json"))) {
139
+ if (at === project.root)
140
+ return `${name} (declared in ${relative(project.root, dir) || "."})`;
141
+ at = dirname(at);
142
+ }
143
+ }
144
144
  }
145
- if (!installIsStale(root)) {
146
- ensuredRoots.add(root);
145
+ return undefined;
146
+ }
147
+ /** Read-only consumers must never install through desired-state loading. */
148
+ export function checkProjectDeps(cwd) {
149
+ const project = findProject(cwd);
150
+ if (!project)
147
151
  return;
152
+ const selected = policy(project, "read");
153
+ const missing = missingDependency(project, true);
154
+ if (missing)
155
+ throw new Error(`Missing project dependency ${missing}. Run '${selected.manager} ${!selected.lock ? "install" : selected.manager === "bun" ? "install --frozen-lockfile" : "ci"} --ignore-scripts' in ${project.root}, then retry.`);
156
+ }
157
+ /** Hold the project lock through compilation so another Lobu install cannot race it. */
158
+ export async function withProjectDependencies(cwd, options, use) {
159
+ const mode = options.mode ?? "frozen";
160
+ if (mode === "read") {
161
+ checkProjectDeps(cwd);
162
+ return use();
148
163
  }
149
- log(`Installing connector dependencies in ${root}...`);
150
- installProjectDeps(root, { stdio: "inherit" });
151
- ensuredRoots.add(root);
164
+ const initial = findProject(cwd);
165
+ if (!initial)
166
+ return use();
167
+ const release = await lockfile.lock(join(initial.root, "package.json"), {
168
+ stale: 300_000,
169
+ update: 10_000,
170
+ retries: { retries: 300, minTimeout: 200, maxTimeout: 200 },
171
+ });
172
+ try {
173
+ const project = findProject(cwd);
174
+ if (!project || project.root !== initial.root)
175
+ throw new Error("Workspace ownership changed during installation. Retry the command.");
176
+ const selected = policy(project, mode);
177
+ const cmd = commandOnPath(selected.manager);
178
+ if (!cmd)
179
+ throw new Error(`Install ${selected.manager}${selected.version ? `@${selected.version}` : ""} and put it on PATH. Lobu will not switch package managers for this project.`);
180
+ const { stdout } = await exec(cmd, ["--version"], { env: process.env });
181
+ const version = stdout.trim();
182
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version) ||
183
+ (selected.version && selected.version !== version)) {
184
+ throw new Error(`Project requires ${selected.manager}@${selected.version ?? "a valid version"}; found ${version}. Install the declared version before applying.`);
185
+ }
186
+ const before = fingerprint(project);
187
+ const key = `${cmd}\0${version}\0${before}`;
188
+ if (mode === "create" ||
189
+ options.session?.get(project.root) !== key ||
190
+ missingDependency(project)) {
191
+ options.session?.delete(project.root);
192
+ options.log?.(`Installing project dependencies with ${selected.manager} in ${project.root}...`);
193
+ const args = selected.manager === "bun"
194
+ ? [
195
+ "install",
196
+ ...(mode === "create" ? [] : ["--frozen-lockfile"]),
197
+ "--ignore-scripts",
198
+ ]
199
+ : [
200
+ mode === "create" ? "install" : "ci",
201
+ "--ignore-scripts",
202
+ "--no-audit",
203
+ "--no-fund",
204
+ "--include=dev",
205
+ ];
206
+ try {
207
+ const child = execFile(cmd, args, {
208
+ cwd: project.root,
209
+ env: { ...process.env, NODE_ENV: "development" },
210
+ maxBuffer: 8 * 1024 * 1024,
211
+ });
212
+ if (options.stdio !== "pipe") {
213
+ child.stdout?.pipe(process.stdout);
214
+ child.stderr?.pipe(process.stderr);
215
+ }
216
+ await new Promise((accept, reject) => {
217
+ child.once("error", reject);
218
+ child.once("exit", (code, signal) => code === 0 ? accept() : reject(new Error(`exit ${code ?? signal}`)));
219
+ });
220
+ }
221
+ catch (error) {
222
+ throw new Error(`${selected.manager} ${args.join(" ")} failed in ${project.root}. Fix the project manifest/lockfile with '${selected.manager} install --ignore-scripts', then retry. ${error instanceof Error ? error.message : String(error)}`);
223
+ }
224
+ if (mode !== "create") {
225
+ const after = findProject(cwd);
226
+ if (!after || before !== fingerprint(after))
227
+ throw new Error("Dependency inputs changed during installation. Retry with a consistent manifest and lockfile.");
228
+ const missing = missingDependency(project);
229
+ if (missing)
230
+ throw new Error(`Installation did not provide project dependency ${missing}. Check the package manager configuration in ${project.root}.`);
231
+ options.session?.set(project.root, key);
232
+ }
233
+ }
234
+ return await use();
235
+ }
236
+ finally {
237
+ await release();
238
+ }
239
+ }
240
+ /** Init alone may create/update the project's lockfile. */
241
+ export async function installProjectDeps(root, opts = {}) {
242
+ await withProjectDependencies(root, { ...opts, mode: "create" }, async () => undefined);
152
243
  }
153
244
  //# sourceMappingURL=ensure-deps-installed.js.map
@@ -0,0 +1,33 @@
1
+ import type { RetainedSource } from "@lobu/core/contracts/tools/source-files";
2
+ export interface ViewMetadata {
3
+ key: string;
4
+ attach: Array<Record<string, unknown>>;
5
+ params: Record<string, unknown>;
6
+ actions: Record<string, {
7
+ emits: string;
8
+ }>;
9
+ }
10
+ export interface BundledView extends RetainedSource {
11
+ compiledCode: string;
12
+ metadata: ViewMetadata;
13
+ }
14
+ /**
15
+ * Bundle the view at `entry` (absolute path) for the browser. Throws when the
16
+ * module has no `view` export, no default-export component, or an invalid
17
+ * key — all fail loud at apply time, never as a blank frame.
18
+ */
19
+ export declare function bundleViewFromFile(entry: string, projectRoot: string): Promise<BundledView>;
20
+ /**
21
+ * The `lobu run` watch set for one view: the entry plus every file esbuild
22
+ * pulled in (relative components, shared lib), from the metafile — so editing
23
+ * an imported file rebuilds the view. Returned as absolute paths.
24
+ */
25
+ export declare function collectViewWatchFiles(entry: string): Promise<string[]>;
26
+ /**
27
+ * Generated bundles must be portable: no developer home, checkout, or worktree
28
+ * directory may leak into the shipped bytes (or the stored view breaks on any
29
+ * other machine and leaks machine state). esbuild emits relative names by
30
+ * default; this is the backstop that fails the apply when it does not.
31
+ */
32
+ export declare function assertBundlePortable(compiledCode: string, entry: string): void;
33
+ //# sourceMappingURL=view-bundler.d.ts.map
@@ -0,0 +1,207 @@
1
+ /**
2
+ * Bundle a Lobu view module for the browser and extract its metadata.
3
+ *
4
+ * The module shape is exactly one: `export const view = defineView({ key,
5
+ * attach, … })` plus a default-export component (hooks inside, no document
6
+ * access). Two esbuild passes over the same module:
7
+ * 1. browser IIFE bundle of a SYNTHETIC entry that mounts the two exports
8
+ * (`mountView(view, Default)`) — what the server stores as
9
+ * `compiled_code` and inlines into the view shell. Bundled here, where
10
+ * the project's node_modules exists (the same path custom connectors
11
+ * use), because the server has no file context for relative imports or
12
+ * view npm deps. The server compiles plain sources itself through the
13
+ * same mount on its own bootstrap.
14
+ * 2. a node bundle of the module in which `@lobu/views` is replaced by a
15
+ * stub, imported only to read the `view` export — so `key`/`attach`/
16
+ * `params`/`actions` come from the module itself. The attach line lives
17
+ * in the file, never in the config.
18
+ *
19
+ * Anything else (no `view` export, no default component, bad key) fails loud
20
+ * here rather than rendering a blank frame in prod.
21
+ */
22
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
23
+ import { tmpdir } from "node:os";
24
+ import { basename, dirname, join, resolve } from "node:path";
25
+ import { pathToFileURL } from "node:url";
26
+ import { build } from "esbuild";
27
+ import { createSourceCapture } from "../../internal/connector-compiler.js";
28
+ const VIEW_KEY_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
29
+ const RUNTIME_MODULE_RE = /(^|\/)lobu-views(\.tsx?)?$|^@lobu\/views$/;
30
+ const metadataStub = {
31
+ name: "lobu-views-metadata-stub",
32
+ setup(b) {
33
+ b.onResolve({ filter: RUNTIME_MODULE_RE }, () => ({
34
+ path: "lobu-views-stub",
35
+ namespace: "lobu-views-stub",
36
+ }));
37
+ b.onLoad({ filter: /.*/, namespace: "lobu-views-stub" }, () => ({
38
+ loader: "js",
39
+ contents: `
40
+ export function defineView(def) {
41
+ if (!def || typeof def.key !== "string" || !def.key) {
42
+ throw new Error("defineView({ key, attach, ... }) requires a non-empty key");
43
+ }
44
+ return def;
45
+ }
46
+ export function mountView() { throw new Error("mountView is not called by view modules: export const view = defineView({ ... }) plus a default-export component"); }
47
+ const noHook = () => { throw new Error("hooks are not available at metadata-extraction time"); };
48
+ export const useParams = noHook, useScope = noHook, useHost = noHook,
49
+ useQuery = noHook, useAction = noHook;
50
+ export function Provider() { throw new Error("not available at metadata-extraction time"); }
51
+ export function sql(strings, ...values) { return { kind: "sql", text: String(strings[0] ?? "") }; }
52
+ export function tool(name, args = {}) { return { kind: "tool", name, args }; }
53
+ export function escapeLiteral(value) { return String(value); }
54
+ export const defaultsFor = () => ({}), coerceParams = (_def, raw) => raw ?? {};
55
+ `,
56
+ }));
57
+ },
58
+ };
59
+ function readViewExport(ns, entry) {
60
+ const view = ns?.view;
61
+ if (!view || typeof view !== "object") {
62
+ throw new Error(`${entry}: the module must export const view = defineView({ key, attach, ... })`);
63
+ }
64
+ const { key } = view;
65
+ if (typeof key !== "string" || !key) {
66
+ throw new Error(`${entry}: defineView({ key, attach, ... }) requires a non-empty key`);
67
+ }
68
+ return {
69
+ view: { ...view, key },
70
+ hasDefault: typeof ns?.default === "function",
71
+ };
72
+ }
73
+ /**
74
+ * Bundle the view at `entry` (absolute path) for the browser. Throws when the
75
+ * module has no `view` export, no default-export component, or an invalid
76
+ * key — all fail loud at apply time, never as a blank frame.
77
+ */
78
+ export async function bundleViewFromFile(entry, projectRoot) {
79
+ const dir = dirname(resolve(entry));
80
+ const rel = `./${basename(entry)}`;
81
+ const capture = createSourceCapture(entry, projectRoot);
82
+ const browser = await build({
83
+ plugins: [capture.plugin],
84
+ stdin: {
85
+ contents: `import { mountView } from "@lobu/views";\nimport * as mod from ${JSON.stringify(rel)};\nmountView(mod.view, mod.default);\n`,
86
+ loader: "tsx",
87
+ resolveDir: dir,
88
+ },
89
+ bundle: true,
90
+ write: false,
91
+ format: "iife",
92
+ platform: "browser",
93
+ target: ["es2022"],
94
+ jsx: "automatic",
95
+ minify: true,
96
+ sourcemap: false,
97
+ legalComments: "none",
98
+ define: { "process.env.NODE_ENV": '"production"' },
99
+ logLevel: "silent",
100
+ });
101
+ const compiledCode = browser.outputFiles?.[0]?.text ?? "";
102
+ if (!compiledCode) {
103
+ throw new Error(`${entry}: view bundle compiled to empty output`);
104
+ }
105
+ assertBundlePortable(compiledCode, entry);
106
+ const node = await build({
107
+ entryPoints: [entry],
108
+ bundle: true,
109
+ write: false,
110
+ format: "esm",
111
+ platform: "node",
112
+ target: ["node22"],
113
+ jsx: "automatic",
114
+ plugins: [capture.plugin, metadataStub],
115
+ define: { "process.env.NODE_ENV": '"production"' },
116
+ logLevel: "silent",
117
+ });
118
+ const tmp = await mkdtemp(join(tmpdir(), "lobu-view-meta-"));
119
+ try {
120
+ const file = join(tmp, "view.mjs");
121
+ await writeFile(file, node.outputFiles?.[0]?.text ?? "");
122
+ // A fresh temp path per call, so the ESM cache never returns a stale module.
123
+ const ns = await import(pathToFileURL(file).href);
124
+ const { view: def, hasDefault } = readViewExport(ns, entry);
125
+ if (!hasDefault) {
126
+ throw new Error(`${entry}: the module must have a default-export component`);
127
+ }
128
+ if (!VIEW_KEY_RE.test(def.key)) {
129
+ throw new Error(`${entry}: defineView key ${JSON.stringify(def.key)} must match /^[a-z0-9][a-z0-9-]{0,63}$/`);
130
+ }
131
+ return {
132
+ compiledCode,
133
+ ...capture.source(),
134
+ metadata: {
135
+ key: def.key,
136
+ attach: Array.isArray(def.attach) ? def.attach : [],
137
+ params: def.params && typeof def.params === "object"
138
+ ? def.params
139
+ : {},
140
+ actions: def.actions && typeof def.actions === "object"
141
+ ? def.actions
142
+ : {},
143
+ },
144
+ };
145
+ }
146
+ finally {
147
+ await rm(tmp, { recursive: true, force: true });
148
+ }
149
+ }
150
+ /**
151
+ * The `lobu run` watch set for one view: the entry plus every file esbuild
152
+ * pulled in (relative components, shared lib), from the metafile — so editing
153
+ * an imported file rebuilds the view. Returned as absolute paths.
154
+ */
155
+ export async function collectViewWatchFiles(entry) {
156
+ // The build directory is explicit and absolute: metafile input names are
157
+ // relative to it, so they must be resolved against this exact directory.
158
+ // Previously the build ran with an implicit ambient cwd while inputs were
159
+ // resolved against the entry directory, duplicating path segments for
160
+ // views below the project root and registering nonexistent watch paths.
161
+ const workdir = dirname(resolve(entry));
162
+ const result = await build({
163
+ entryPoints: [entry],
164
+ absWorkingDir: workdir,
165
+ bundle: true,
166
+ write: false,
167
+ format: "esm",
168
+ platform: "browser",
169
+ jsx: "automatic",
170
+ metafile: true,
171
+ logLevel: "silent",
172
+ });
173
+ const metafile = result.metafile;
174
+ if (!metafile)
175
+ return [resolve(entry)];
176
+ const files = new Set([resolve(entry)]);
177
+ for (const input of Object.keys(metafile.inputs)) {
178
+ // Absolute keys pass through; relative keys are relative to workdir.
179
+ files.add(resolve(workdir, input));
180
+ }
181
+ return [...files].sort();
182
+ }
183
+ /**
184
+ * Generated bundles must be portable: no developer home, checkout, or worktree
185
+ * directory may leak into the shipped bytes (or the stored view breaks on any
186
+ * other machine and leaks machine state). esbuild emits relative names by
187
+ * default; this is the backstop that fails the apply when it does not.
188
+ */
189
+ export function assertBundlePortable(compiledCode, entry) {
190
+ const suspects = [entry, dirname(entry)];
191
+ const home = process.env.HOME ?? process.env.USERPROFILE;
192
+ if (home)
193
+ suspects.push(home);
194
+ for (const suspect of suspects) {
195
+ if (suspect && compiledCode.includes(suspect)) {
196
+ throw new Error(`view bundle embeds the local path ${JSON.stringify(suspect)} — bundles must be portable`);
197
+ }
198
+ }
199
+ const encoded = compiledCode.match(/file:\/\/[^"'\s]*/g) ?? [];
200
+ for (const url of encoded) {
201
+ // A browser bundle has no business with file URLs: any of them embeds a
202
+ // build-machine path (or its encoding), so reject the bundle outright
203
+ // rather than trying to tell ours from a legitimate one.
204
+ throw new Error(`view bundle embeds a file URL ${JSON.stringify(url)} — bundles must be portable`);
205
+ }
206
+ }
207
+ //# sourceMappingURL=view-bundler.js.map