@objectstack/runtime 9.0.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -381,7 +381,7 @@ var init_quickjs_runner = __esm({
381
381
  evalRes.value.dispose();
382
382
  let pumps = 0;
383
383
  while (pumps < 1e3) {
384
- await new Promise((resolve2) => setImmediate(resolve2));
384
+ await new Promise((resolve) => setImmediate(resolve));
385
385
  const pending = runtime.executePendingJobs();
386
386
  if (pending.error) {
387
387
  const err = vm.dump(pending.error);
@@ -1160,8 +1160,8 @@ var init_app_plugin = __esm({
1160
1160
  }
1161
1161
  })();
1162
1162
  let timer;
1163
- const budget = new Promise((resolve2) => {
1164
- timer = setTimeout(() => resolve2("budget"), seedBudgetMs);
1163
+ const budget = new Promise((resolve) => {
1164
+ timer = setTimeout(() => resolve("budget"), seedBudgetMs);
1165
1165
  });
1166
1166
  const winner = await Promise.race([seedPromise.then(() => "done"), budget]);
1167
1167
  if (timer) clearTimeout(timer);
@@ -2053,7 +2053,13 @@ function randomUUID() {
2053
2053
  });
2054
2054
  }
2055
2055
  var _HttpDispatcher = class _HttpDispatcher {
2056
- constructor(kernel, envRegistry, options) {
2056
+ /**
2057
+ * @param _envRegistryIgnored — RETIRED (ADR-0006 Phase 5). Environment
2058
+ * resolution moved behind the host's {@link KernelResolver}; the
2059
+ * positional parameter is kept so existing 3-arg callers keep compiling,
2060
+ * but its value is ignored.
2061
+ */
2062
+ constructor(kernel, _envRegistryIgnored, options) {
2057
2063
  /**
2058
2064
  * In-memory cache of positive membership checks, keyed by
2059
2065
  * `${environmentId}:${userId}`. Entries expire 60 seconds after insertion
@@ -2070,9 +2076,8 @@ var _HttpDispatcher = class _HttpDispatcher {
2070
2076
  return void 0;
2071
2077
  }
2072
2078
  };
2073
- this.envRegistry = envRegistry ?? resolveService("env-registry");
2074
2079
  this.enforceMembership = options?.enforceProjectMembership ?? true;
2075
- this.kernelManager = options?.kernelManager ?? resolveService("kernel-manager");
2080
+ this.kernelResolver = options?.kernelResolver ?? resolveService("kernel-resolver");
2076
2081
  this.scopeManager = options?.scopeManager ?? resolveService("scope-manager");
2077
2082
  }
2078
2083
  resolveDefaultProject() {
@@ -2460,130 +2465,20 @@ var _HttpDispatcher = class _HttpDispatcher {
2460
2465
  return candidate;
2461
2466
  }
2462
2467
  /**
2463
- * Resolve environment context for incoming request.
2464
- *
2465
- * Precedence:
2466
- * 0. URL path matches `/environments/:environmentId/...` OR request.params.environmentId set by router
2467
- * → envRegistry.resolveById(id)
2468
- * 1. request.headers.host → envRegistry.resolveByHostname(host)
2469
- * 2. request.headers['x-environment-id'] → envRegistry.resolveById(id)
2470
- * 3. session.activeEnvironmentId → envRegistry.resolveById(id)
2471
- * 4. session.activeOrganizationId → find default project → envRegistry.resolveById(id)
2472
- * 5. single-environment default (registered by `createSingleEnvironmentPlugin`)
2473
- * → envRegistry.resolveById(defaultProject.environmentId). Lets bare
2474
- * `/api/v1/data/...` URLs resolve to the lone project in
2475
- * `cloudUrl: 'local'` deployments.
2468
+ * Attach the dispatcher's parsing hints for the host's
2469
+ * {@link KernelResolver} (ADR-0006 Phase 5).
2476
2470
  *
2477
- * Skip for paths: /auth, /cloud, /health, /discovery (NOT /meta when scoped,
2478
- * so project-scoped meta routes can resolve their project).
2471
+ * Environment RESOLUTION (hostname / x-environment-id / session /
2472
+ * org-default / single-env-default environment + driver) is owned by
2473
+ * the host's resolver — the dispatcher no longer touches an environment
2474
+ * registry. What stays here is pure URL parsing (the dispatcher's own
2475
+ * routing convention): the scoped-path environment-id candidate and the
2476
+ * cleaned route path, both UNVALIDATED.
2479
2477
  */
2480
- async resolveEnvironmentContext(context, path) {
2481
- const skipPaths = ["/cloud", "/health", "/discovery"];
2482
- if (skipPaths.some((p) => path.startsWith(p))) {
2483
- return;
2484
- }
2485
- if (!this.envRegistry) {
2486
- return;
2487
- }
2488
- const headers = context.request?.headers;
2489
- const getHeader = (name) => {
2490
- if (!headers) return void 0;
2491
- const h = headers;
2492
- if (typeof h.get === "function") {
2493
- const v = h.get(name);
2494
- return v == null ? void 0 : String(v);
2495
- }
2496
- const lower = name.toLowerCase();
2497
- for (const k of Object.keys(h)) {
2498
- if (k.toLowerCase() === lower) {
2499
- const v = h[k];
2500
- return Array.isArray(v) ? v[0] : v == null ? void 0 : String(v);
2501
- }
2502
- }
2503
- return void 0;
2504
- };
2505
- try {
2506
- const urlEnvironmentId = this.extractEnvironmentIdFromPath(path) ?? context.request?.params?.environmentId;
2507
- if (urlEnvironmentId) {
2508
- const driver = await this.envRegistry.resolveById(urlEnvironmentId);
2509
- if (driver) {
2510
- context.environmentId = urlEnvironmentId;
2511
- context.dataDriver = driver;
2512
- return;
2513
- }
2514
- }
2515
- const host = getHeader("host");
2516
- if (host) {
2517
- const hostname = host.split(":")[0];
2518
- const result = await this.envRegistry.resolveByHostname(hostname);
2519
- if (result) {
2520
- context.environmentId = result.environmentId;
2521
- context.dataDriver = result.driver;
2522
- return;
2523
- }
2524
- }
2525
- const envIdHeader = getHeader("x-environment-id");
2526
- if (envIdHeader) {
2527
- const driver = await this.envRegistry.resolveById(envIdHeader);
2528
- if (driver) {
2529
- context.environmentId = envIdHeader;
2530
- context.dataDriver = driver;
2531
- return;
2532
- }
2533
- }
2534
- try {
2535
- const authService = await this.getService(CoreServiceName.enum.auth);
2536
- const sessionData = await authService?.api?.getSession?.({
2537
- headers: context.request?.headers
2538
- });
2539
- const activeEnvironmentId = sessionData?.session?.activeEnvironmentId ?? sessionData?.session?.activeEnvironmentId;
2540
- if (activeEnvironmentId) {
2541
- const driver = await this.envRegistry.resolveById(activeEnvironmentId);
2542
- if (driver) {
2543
- context.environmentId = activeEnvironmentId;
2544
- context.dataDriver = driver;
2545
- return;
2546
- }
2547
- }
2548
- const activeOrganizationId = sessionData?.session?.activeOrganizationId;
2549
- if (activeOrganizationId) {
2550
- const qlService = await this.getObjectQLService();
2551
- const ql = qlService ?? await this.resolveService("objectql");
2552
- if (ql) {
2553
- let rows = await ql.find("sys_environment", {
2554
- where: {
2555
- organization_id: activeOrganizationId,
2556
- is_default: true
2557
- },
2558
- limit: 1
2559
- });
2560
- if (rows && rows.value) rows = rows.value;
2561
- if (Array.isArray(rows) && rows[0]) {
2562
- const defaultEnv = rows[0];
2563
- const driver = await this.envRegistry.resolveById(defaultEnv.id);
2564
- if (driver) {
2565
- context.environmentId = defaultEnv.id;
2566
- context.dataDriver = driver;
2567
- return;
2568
- }
2569
- }
2570
- }
2571
- }
2572
- } catch (sessionError) {
2573
- console.debug("[HttpDispatcher] Session resolution failed:", sessionError);
2574
- }
2575
- if (this.defaultProject?.environmentId || this.resolveDefaultProject()) {
2576
- const def = this.defaultProject;
2577
- const driver = await this.envRegistry.resolveById(def.environmentId);
2578
- if (driver) {
2579
- context.environmentId = def.environmentId;
2580
- context.dataDriver = driver;
2581
- return;
2582
- }
2583
- }
2584
- } catch (error) {
2585
- console.error("[HttpDispatcher] Environment resolution failed:", error);
2586
- }
2478
+ prepareResolverHints(context, path) {
2479
+ context.routePath = path;
2480
+ const urlEnvironmentId = this.extractEnvironmentIdFromPath(path) ?? context.request?.params?.environmentId;
2481
+ if (urlEnvironmentId) context.urlEnvironmentId = String(urlEnvironmentId);
2587
2482
  }
2588
2483
  /**
2589
2484
  * Check whether the authenticated user is a member of
@@ -3106,7 +3001,7 @@ var _HttpDispatcher = class _HttpDispatcher {
3106
3001
  if (!objectName) {
3107
3002
  return { handled: true, response: this.error("Object name required", 400) };
3108
3003
  }
3109
- if (!_context.dataDriver && this.envRegistry) {
3004
+ if (!_context.dataDriver && this.kernelResolver) {
3110
3005
  return {
3111
3006
  handled: true,
3112
3007
  response: this.error("Project not resolved. Please specify X-Environment-Id header or ensure hostname maps to a project.", 428)
@@ -4007,9 +3902,9 @@ var _HttpDispatcher = class _HttpDispatcher {
4007
3902
  if (def?.environmentId) _context.environmentId = def.environmentId;
4008
3903
  }
4009
3904
  let projectQl = null;
4010
- if (this.kernelManager && _context.environmentId && _context.environmentId !== "platform") {
3905
+ if (this.kernelResolver && _context.environmentId && _context.environmentId !== "platform") {
4011
3906
  try {
4012
- const projectKernel = await this.kernelManager.getOrCreate(_context.environmentId);
3907
+ const projectKernel = await this.kernelResolver.resolveKernel(_context, this.defaultKernel);
4013
3908
  if (projectKernel) {
4014
3909
  this.kernel = projectKernel;
4015
3910
  if (typeof projectKernel.getServiceAsync === "function") {
@@ -4182,9 +4077,9 @@ var _HttpDispatcher = class _HttpDispatcher {
4182
4077
  */
4183
4078
  async dispatch(method, path, body, query, context, prefix) {
4184
4079
  let cleanPath = path.replace(/\/$/, "");
4185
- await this.resolveEnvironmentContext(context, cleanPath);
4186
- if (this.kernelManager && context.environmentId && context.environmentId !== "platform") {
4187
- this.kernel = await this.kernelManager.getOrCreate(context.environmentId);
4080
+ this.prepareResolverHints(context, cleanPath);
4081
+ if (this.kernelResolver) {
4082
+ this.kernel = await this.kernelResolver.resolveKernel(context, this.defaultKernel) ?? this.defaultKernel;
4188
4083
  } else {
4189
4084
  this.kernel = this.defaultKernel;
4190
4085
  }
@@ -5620,1088 +5515,6 @@ var MiddlewareManager = class {
5620
5515
  // src/index.ts
5621
5516
  init_load_artifact_bundle();
5622
5517
 
5623
- // src/cloud/cloud-url.ts
5624
- var DEFAULT_CLOUD_URL = "https://cloud.objectos.ai";
5625
- function resolveCloudUrl(explicit) {
5626
- const raw = (explicit ?? process.env.OS_CLOUD_URL ?? "").trim();
5627
- const lower = raw.toLowerCase();
5628
- if (lower === "off" || lower === "none" || lower === "local" || lower === "disabled") {
5629
- return "";
5630
- }
5631
- const picked = raw || DEFAULT_CLOUD_URL;
5632
- return picked.replace(/\/+$/, "");
5633
- }
5634
-
5635
- // src/cloud/marketplace-public-url.ts
5636
- function resolveMarketplacePublicBaseUrl(explicit) {
5637
- const raw = (explicit ?? process.env.OS_MARKETPLACE_PUBLIC_BASE_URL ?? "").trim();
5638
- const lower = raw.toLowerCase();
5639
- if (!raw || lower === "off" || lower === "none" || lower === "disabled" || lower === "false") {
5640
- return "";
5641
- }
5642
- return raw.replace(/\/+$/, "");
5643
- }
5644
- function publicMarketplaceKeyForApiPath(pathname) {
5645
- const prefix = "/api/v1/marketplace/packages";
5646
- if (pathname === prefix) return "packages.json";
5647
- if (!pathname.startsWith(`${prefix}/`)) return null;
5648
- const tail = pathname.slice(prefix.length + 1);
5649
- if (!tail) return null;
5650
- const parts = tail.split("/");
5651
- if (parts.length === 1) {
5652
- const id = decodeURIComponent(parts[0] ?? "");
5653
- if (!id) return null;
5654
- return `packages/${encodeURIComponent(id)}.json`;
5655
- }
5656
- if (parts.length === 4 && parts[1] === "versions" && parts[3] === "manifest") {
5657
- const id = decodeURIComponent(parts[0] ?? "");
5658
- const versionId = decodeURIComponent(parts[2] ?? "");
5659
- if (!id || !versionId) return null;
5660
- return `packages/${encodeURIComponent(id)}/versions/${encodeURIComponent(versionId)}/manifest.json`;
5661
- }
5662
- return null;
5663
- }
5664
-
5665
- // src/cloud/marketplace-proxy-plugin.ts
5666
- var MARKETPLACE_PREFIX = "/api/v1/marketplace";
5667
- var DEFAULT_LRU_MAX = 200;
5668
- var LIST_TTL_MS = 30 * 60 * 1e3;
5669
- var PACKAGE_TTL_MS = 2 * 60 * 60 * 1e3;
5670
- var VERSION_TTL_MS = 24 * 60 * 60 * 1e3;
5671
- function ttlForPath(pathname) {
5672
- if (/\/packages\/[^/]+\/versions\//.test(pathname)) return VERSION_TTL_MS;
5673
- if (/\/packages\/[^/]+/.test(pathname)) return PACKAGE_TTL_MS;
5674
- return LIST_TTL_MS;
5675
- }
5676
- var LruTtlCache = class {
5677
- constructor(max) {
5678
- this.max = max;
5679
- this.map = /* @__PURE__ */ new Map();
5680
- }
5681
- get(key) {
5682
- const entry = this.map.get(key);
5683
- if (!entry) return void 0;
5684
- this.map.delete(key);
5685
- this.map.set(key, entry);
5686
- return entry;
5687
- }
5688
- set(key, entry) {
5689
- if (this.map.has(key)) this.map.delete(key);
5690
- this.map.set(key, entry);
5691
- while (this.map.size > this.max) {
5692
- const oldest = this.map.keys().next().value;
5693
- if (oldest === void 0) break;
5694
- this.map.delete(oldest);
5695
- }
5696
- }
5697
- clear() {
5698
- this.map.clear();
5699
- }
5700
- };
5701
- var MarketplaceProxyPlugin = class _MarketplaceProxyPlugin {
5702
- constructor(config = {}) {
5703
- this.name = "com.objectstack.runtime.marketplace-proxy";
5704
- this.version = "1.1.0";
5705
- this.init = async (_ctx) => {
5706
- };
5707
- this.start = async (ctx) => {
5708
- ctx.hook("kernel:ready", async () => {
5709
- let httpServer;
5710
- try {
5711
- httpServer = ctx.getService("http-server");
5712
- } catch {
5713
- ctx.logger?.warn?.("[MarketplaceProxyPlugin] http-server not available \u2014 marketplace routes not mounted");
5714
- return;
5715
- }
5716
- if (!httpServer || typeof httpServer.getRawApp !== "function") {
5717
- ctx.logger?.warn?.("[MarketplaceProxyPlugin] http-server missing getRawApp() \u2014 marketplace routes not mounted");
5718
- return;
5719
- }
5720
- const rawApp = httpServer.getRawApp();
5721
- const cloudUrl = this.cloudUrl;
5722
- const publicBaseUrl = this.publicBaseUrl;
5723
- const cache = this.cache;
5724
- if (publicBaseUrl) {
5725
- ctx.logger?.info?.(`[MarketplaceProxyPlugin] public R2 fast-path enabled \u2192 ${publicBaseUrl}`);
5726
- }
5727
- const handler = async (c, next) => {
5728
- if (!cloudUrl) {
5729
- return c.json({
5730
- success: false,
5731
- error: {
5732
- code: "marketplace_unavailable",
5733
- message: "No control-plane URL configured for this runtime (OS_CLOUD_URL)."
5734
- }
5735
- }, 503);
5736
- }
5737
- try {
5738
- const incomingUrl = new URL(c.req.url);
5739
- if (incomingUrl.pathname.startsWith(`${MARKETPLACE_PREFIX}/install-local`)) {
5740
- return next();
5741
- }
5742
- const method = String(c.req.method ?? "GET").toUpperCase();
5743
- if (publicBaseUrl && (method === "GET" || method === "HEAD")) {
5744
- const r2Resp = await tryPublicMarketplaceFetch(
5745
- publicBaseUrl,
5746
- incomingUrl,
5747
- method,
5748
- c.req.header("accept"),
5749
- ctx.logger
5750
- );
5751
- if (r2Resp) return r2Resp;
5752
- }
5753
- const target = `${cloudUrl}${incomingUrl.pathname}${incomingUrl.search}`;
5754
- if (method !== "GET" && method !== "HEAD") {
5755
- return next();
5756
- }
5757
- const accept = c.req.header("accept") ?? "application/json";
5758
- const acceptLang = c.req.header("accept-language") ?? "";
5759
- const cacheKey = `${incomingUrl.pathname}${incomingUrl.search}|al=${acceptLang}|a=${accept}`;
5760
- const reqCacheCtl = (c.req.header("cache-control") ?? "").toLowerCase();
5761
- const bypass = !cache || reqCacheCtl.includes("no-cache") || reqCacheCtl.includes("no-store");
5762
- const now = Date.now();
5763
- if (cache && !bypass) {
5764
- const hit = cache.get(cacheKey);
5765
- if (hit && hit.expiresAt > now) {
5766
- return buildCachedResponse(hit, method, "HIT");
5767
- }
5768
- if (hit) {
5769
- const revalHeaders = {
5770
- "Accept": accept,
5771
- "User-Agent": `objectos-marketplace-proxy/${_MarketplaceProxyPlugin.prototype.version ?? "1.0.0"}`
5772
- };
5773
- if (acceptLang) revalHeaders["Accept-Language"] = acceptLang;
5774
- if (hit.etag) revalHeaders["If-None-Match"] = hit.etag;
5775
- if (hit.lastModified) revalHeaders["If-Modified-Since"] = hit.lastModified;
5776
- const revalResp = await fetch(target, { method: "GET", headers: revalHeaders });
5777
- if (revalResp.status === 304) {
5778
- hit.expiresAt = now + hit.ttlMs;
5779
- const newEtag = revalResp.headers.get("etag");
5780
- const newLm = revalResp.headers.get("last-modified");
5781
- if (newEtag) hit.etag = newEtag;
5782
- if (newLm) hit.lastModified = newLm;
5783
- cache.set(cacheKey, hit);
5784
- return buildCachedResponse(hit, method, "REVALIDATED");
5785
- }
5786
- return await consumeAndMaybeCache(revalResp, cacheKey, incomingUrl.pathname, method, cache);
5787
- }
5788
- }
5789
- const reqHeaders = {
5790
- // Strip the inbound Host header — fetch will set
5791
- // it to the cloud host. Forward only the
5792
- // identifying headers cloud might log.
5793
- "Accept": accept,
5794
- "User-Agent": `objectos-marketplace-proxy/${_MarketplaceProxyPlugin.prototype.version ?? "1.0.0"}`
5795
- };
5796
- if (acceptLang) reqHeaders["Accept-Language"] = acceptLang;
5797
- const resp = await fetch(target, { method: "GET", headers: reqHeaders });
5798
- if (bypass || !cache) {
5799
- return await passthroughResponse(resp, method, bypass ? "BYPASS" : "MISS");
5800
- }
5801
- return await consumeAndMaybeCache(resp, cacheKey, incomingUrl.pathname, method, cache);
5802
- } catch (err) {
5803
- const errObj = err instanceof Error ? err : new Error(err?.message ?? String(err));
5804
- ctx.logger?.error?.("[MarketplaceProxyPlugin] proxy failed", errObj);
5805
- return c.json({
5806
- success: false,
5807
- error: {
5808
- code: "marketplace_proxy_failed",
5809
- message: err?.message ?? String(err)
5810
- }
5811
- }, 502);
5812
- }
5813
- };
5814
- if (typeof rawApp.all === "function") {
5815
- rawApp.all(`${MARKETPLACE_PREFIX}/*`, handler);
5816
- } else {
5817
- for (const m of ["get", "head"]) {
5818
- try {
5819
- rawApp[m]?.(`${MARKETPLACE_PREFIX}/*`, handler);
5820
- } catch {
5821
- }
5822
- }
5823
- }
5824
- ctx.logger?.info?.(`[MarketplaceProxyPlugin] mounted at ${MARKETPLACE_PREFIX}/* \u2192 ${cloudUrl || "(unconfigured)"} (cache=${this.cache ? "on" : "off"})`);
5825
- });
5826
- };
5827
- this.cloudUrl = resolveCloudUrl(config.controlPlaneUrl);
5828
- this.publicBaseUrl = resolveMarketplacePublicBaseUrl(config.publicMarketplaceBaseUrl);
5829
- const envFlag = (process.env.OS_MARKETPLACE_CACHE ?? "").trim().toLowerCase();
5830
- const envDisabled = ["off", "false", "0", "no", "disable", "disabled"].includes(envFlag);
5831
- const disabled = config.cacheDisabled ?? envDisabled;
5832
- this.cache = disabled ? null : new LruTtlCache(Math.max(8, config.cacheMaxEntries ?? DEFAULT_LRU_MAX));
5833
- }
5834
- };
5835
- async function tryPublicMarketplaceFetch(publicBaseUrl, incomingUrl, method, acceptHeader, logger) {
5836
- const key = publicMarketplaceKeyForApiPath(incomingUrl.pathname);
5837
- if (!key) return null;
5838
- const target = `${publicBaseUrl}/${key}`;
5839
- let resp;
5840
- try {
5841
- resp = await fetch(target, {
5842
- method: "GET",
5843
- headers: {
5844
- "Accept": acceptHeader || "application/json",
5845
- "User-Agent": `objectos-marketplace-proxy/public-r2`
5846
- }
5847
- });
5848
- } catch (err) {
5849
- logger?.warn?.(`[MarketplaceProxyPlugin] public R2 fetch failed (${target}): ${err?.message ?? err}`);
5850
- return null;
5851
- }
5852
- if (resp.status === 404) return null;
5853
- if (!resp.ok) {
5854
- logger?.warn?.(`[MarketplaceProxyPlugin] public R2 ${target} returned ${resp.status} \u2014 falling back to cloud`);
5855
- return null;
5856
- }
5857
- const isList = key === "packages.json";
5858
- const hasFilters = isList && (incomingUrl.searchParams.has("q") || incomingUrl.searchParams.has("category") || incomingUrl.searchParams.has("limit") || incomingUrl.searchParams.has("offset"));
5859
- if (!hasFilters) {
5860
- const headers2 = new Headers();
5861
- const ct = resp.headers.get("content-type") ?? "application/json; charset=utf-8";
5862
- headers2.set("content-type", ct);
5863
- const cc = resp.headers.get("cache-control");
5864
- if (cc) headers2.set("cache-control", cc);
5865
- const etag = resp.headers.get("etag");
5866
- if (etag) headers2.set("etag", etag);
5867
- headers2.set("x-cache", "PUBLIC-R2");
5868
- const body2 = method === "HEAD" ? null : resp.body;
5869
- return new Response(body2, { status: 200, headers: headers2 });
5870
- }
5871
- let snapshot;
5872
- try {
5873
- snapshot = await resp.json();
5874
- } catch (err) {
5875
- logger?.warn?.(`[MarketplaceProxyPlugin] public R2 list snapshot parse failed: ${err?.message ?? err}`);
5876
- return null;
5877
- }
5878
- const items = Array.isArray(snapshot?.data?.items) ? snapshot.data.items : [];
5879
- const q = (incomingUrl.searchParams.get("q") ?? "").trim().toLowerCase();
5880
- const category = (incomingUrl.searchParams.get("category") ?? "").trim();
5881
- const limit = Math.min(Math.max(Number(incomingUrl.searchParams.get("limit") ?? 50), 1), 100);
5882
- const offset = Math.max(Number(incomingUrl.searchParams.get("offset") ?? 0), 0);
5883
- let filtered = items;
5884
- if (q) {
5885
- filtered = filtered.filter((r) => {
5886
- const dn = String(r?.display_name ?? "").toLowerCase();
5887
- const mid = String(r?.manifest_id ?? "").toLowerCase();
5888
- return dn.includes(q) || mid.includes(q);
5889
- });
5890
- }
5891
- if (category) {
5892
- filtered = filtered.filter((r) => String(r?.category ?? "") === category);
5893
- }
5894
- const total = filtered.length;
5895
- const page = filtered.slice(offset, offset + limit);
5896
- const body = JSON.stringify({ success: true, data: { items: page, total, limit, offset } });
5897
- const headers = new Headers({
5898
- "content-type": "application/json; charset=utf-8",
5899
- "cache-control": "public, max-age=30",
5900
- "x-cache": "PUBLIC-R2-FILTERED"
5901
- });
5902
- return new Response(method === "HEAD" ? null : body, { status: 200, headers });
5903
- }
5904
- var PASSTHROUGH_HEADERS = ["content-type", "cache-control", "etag", "last-modified", "vary"];
5905
- function collectHeaders(src) {
5906
- const out = {};
5907
- for (const h of PASSTHROUGH_HEADERS) {
5908
- const v = src.headers.get(h);
5909
- if (v) out[h] = v;
5910
- }
5911
- return out;
5912
- }
5913
- function buildCachedResponse(entry, method, xCache) {
5914
- const headers = new Headers(entry.headers);
5915
- headers.set("X-Cache", xCache);
5916
- const ageSec = Math.max(0, Math.floor((entry.expiresAt - entry.ttlMs - Date.now()) / -1e3));
5917
- headers.set("Age", String(Math.max(0, ageSec)));
5918
- const body = method === "HEAD" ? null : entry.body;
5919
- return new Response(body, { status: entry.status, headers });
5920
- }
5921
- async function passthroughResponse(resp, method, xCache) {
5922
- const headers = new Headers(collectHeaders(resp));
5923
- headers.set("X-Cache", xCache);
5924
- if (method === "HEAD") {
5925
- try {
5926
- await resp.arrayBuffer();
5927
- } catch {
5928
- }
5929
- return new Response(null, { status: resp.status, headers });
5930
- }
5931
- const body = await resp.arrayBuffer();
5932
- return new Response(body, { status: resp.status, headers });
5933
- }
5934
- async function consumeAndMaybeCache(resp, key, pathname, method, cache) {
5935
- const body = await resp.arrayBuffer();
5936
- const headers = collectHeaders(resp);
5937
- if (resp.status >= 200 && resp.status < 300) {
5938
- const ttlMs = ttlForPath(pathname);
5939
- const entry = {
5940
- status: resp.status,
5941
- body,
5942
- headers,
5943
- etag: resp.headers.get("etag") ?? void 0,
5944
- lastModified: resp.headers.get("last-modified") ?? void 0,
5945
- expiresAt: Date.now() + ttlMs,
5946
- ttlMs
5947
- };
5948
- cache.set(key, entry);
5949
- }
5950
- const respHeaders = new Headers(headers);
5951
- respHeaders.set("X-Cache", "MISS");
5952
- const outBody = method === "HEAD" ? null : body;
5953
- return new Response(outBody, { status: resp.status, headers: respHeaders });
5954
- }
5955
-
5956
- // src/cloud/marketplace-install-local-plugin.ts
5957
- import { existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync2, readdirSync, unlinkSync, writeFileSync as writeFileSync3 } from "fs";
5958
- import { join as join2, resolve } from "path";
5959
- import { readEnvWithDeprecation as readEnvWithDeprecation3 } from "@objectstack/types";
5960
- var ROUTE_BASE = "/api/v1/marketplace/install-local";
5961
- var DEFAULT_DIR = ".objectstack/installed-packages";
5962
- function safeFilename(manifestId) {
5963
- return manifestId.replace(/[^a-zA-Z0-9._-]/g, "_") + ".json";
5964
- }
5965
- var MarketplaceInstallLocalPlugin = class {
5966
- constructor(config = {}) {
5967
- this.name = "com.objectstack.runtime.marketplace-install-local";
5968
- this.version = "1.0.0";
5969
- this.init = async (_ctx) => {
5970
- };
5971
- this.start = async (ctx) => {
5972
- ctx.hook("kernel:ready", async () => {
5973
- await this.rehydrate(ctx);
5974
- let httpServer;
5975
- try {
5976
- httpServer = ctx.getService("http-server");
5977
- } catch {
5978
- ctx.logger?.warn?.("[MarketplaceInstallLocal] http-server not available \u2014 install endpoints not mounted");
5979
- return;
5980
- }
5981
- if (!httpServer || typeof httpServer.getRawApp !== "function") {
5982
- ctx.logger?.warn?.("[MarketplaceInstallLocal] http-server missing getRawApp() \u2014 install endpoints not mounted");
5983
- return;
5984
- }
5985
- const rawApp = httpServer.getRawApp();
5986
- const postHandler = async (c) => this.handleInstall(c, ctx);
5987
- const getHandler = async (c) => this.handleList(c);
5988
- const deleteHandler = async (c) => this.handleUninstall(c, ctx);
5989
- const reseedHandler = async (c) => this.handleReseed(c, ctx);
5990
- const purgeHandler = async (c) => this.handlePurge(c, ctx);
5991
- if (typeof rawApp.post === "function") rawApp.post(ROUTE_BASE, postHandler);
5992
- if (typeof rawApp.get === "function") rawApp.get(ROUTE_BASE, getHandler);
5993
- if (typeof rawApp.delete === "function") rawApp.delete(`${ROUTE_BASE}/:manifestId`, deleteHandler);
5994
- if (typeof rawApp.post === "function") {
5995
- rawApp.post(`${ROUTE_BASE}/:manifestId/reseed-sample-data`, reseedHandler);
5996
- rawApp.post(`${ROUTE_BASE}/:manifestId/purge-sample-data`, purgeHandler);
5997
- }
5998
- ctx.logger?.info?.(`[MarketplaceInstallLocal] mounted at ${ROUTE_BASE} (storage: ${this.storageDir})`);
5999
- });
6000
- };
6001
- /**
6002
- * Re-register every cached manifest with the kernel's manifest service.
6003
- * Safe to call on a kernel that already has the same manifest_id (the
6004
- * underlying ObjectQL registry overwrites by id, but we still warn so
6005
- * a developer can spot the dev-time clash between their config.ts and
6006
- * a marketplace package).
6007
- */
6008
- this.rehydrate = async (ctx) => {
6009
- const entries = this.readAll();
6010
- if (entries.length === 0) return;
6011
- let manifestService = null;
6012
- try {
6013
- manifestService = ctx.getService("manifest");
6014
- } catch {
6015
- ctx.logger?.warn?.("[MarketplaceInstallLocal] no `manifest` service \u2014 rehydrate skipped");
6016
- return;
6017
- }
6018
- for (const entry of entries) {
6019
- try {
6020
- manifestService.register(entry.manifest);
6021
- try {
6022
- const ql = ctx.getService("objectql");
6023
- if (ql && typeof ql.syncSchemas === "function") await ql.syncSchemas();
6024
- } catch {
6025
- }
6026
- await this.applySideEffects(ctx, entry.manifest, { seedNow: false });
6027
- ctx.logger?.info?.(`[MarketplaceInstallLocal] rehydrated ${entry.manifestId}@${entry.version}`);
6028
- } catch (err) {
6029
- ctx.logger?.error?.(`[MarketplaceInstallLocal] rehydrate failed for ${entry.manifestId}`, err instanceof Error ? err : new Error(String(err)));
6030
- }
6031
- }
6032
- };
6033
- this.handleInstall = async (c, ctx) => {
6034
- const userId = await this.requireAuthenticatedUser(c, ctx);
6035
- if (!userId) {
6036
- return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required to install packages." } }, 401);
6037
- }
6038
- let body = {};
6039
- try {
6040
- body = await c.req.json();
6041
- } catch {
6042
- }
6043
- const inlineManifest = body?.manifest && typeof body.manifest === "object" ? body.manifest : null;
6044
- let manifest;
6045
- let resolvedVersionId;
6046
- let version;
6047
- let packageId;
6048
- if (inlineManifest) {
6049
- manifest = inlineManifest;
6050
- packageId = String(manifest.id ?? manifest.name ?? "").trim();
6051
- version = String(manifest.version ?? "unknown");
6052
- resolvedVersionId = String(body?.versionId ?? version);
6053
- if (!packageId) {
6054
- return c.json({ success: false, error: { code: "invalid_manifest", message: 'Inline manifest must have an "id" or "name".' } }, 400);
6055
- }
6056
- } else {
6057
- if (!this.cloudUrl) {
6058
- return c.json({ success: false, error: { code: "marketplace_unavailable", message: "OS_CLOUD_URL not configured." } }, 503);
6059
- }
6060
- packageId = String(body?.packageId ?? "").trim();
6061
- const versionId = String(body?.versionId ?? "latest").trim() || "latest";
6062
- if (!packageId) {
6063
- return c.json({ success: false, error: { code: "bad_request", message: "packageId is required." } }, 400);
6064
- }
6065
- let payload;
6066
- const publicBase = resolveMarketplacePublicBaseUrl();
6067
- const fetchAttempts = [];
6068
- if (publicBase) {
6069
- fetchAttempts.push({
6070
- label: "public-r2",
6071
- url: `${publicBase}/packages/${encodeURIComponent(packageId)}/versions/${encodeURIComponent(versionId)}/manifest.json`
6072
- });
6073
- }
6074
- fetchAttempts.push({
6075
- label: "cloud",
6076
- url: `${this.cloudUrl}/api/v1/marketplace/packages/${encodeURIComponent(packageId)}/versions/${encodeURIComponent(versionId)}/manifest`
6077
- });
6078
- let lastErrStatus = 0;
6079
- let lastErrText = "";
6080
- for (const attempt of fetchAttempts) {
6081
- try {
6082
- const resp = await fetch(attempt.url, { headers: { "Accept": "application/json" } });
6083
- if (!resp.ok) {
6084
- lastErrStatus = resp.status;
6085
- lastErrText = (await resp.text().catch(() => "")).slice(0, 200);
6086
- if (attempt.label === "public-r2" && resp.status === 404) {
6087
- ctx.logger?.info?.(`[MarketplaceInstallLocal] public-r2 miss for ${packageId}@${versionId}, falling back to cloud`);
6088
- continue;
6089
- }
6090
- if (attempt.label === "public-r2" && resp.status >= 500) {
6091
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] public-r2 ${resp.status}, falling back to cloud`);
6092
- continue;
6093
- }
6094
- break;
6095
- }
6096
- payload = await resp.json();
6097
- lastErrStatus = 0;
6098
- break;
6099
- } catch (err) {
6100
- if (attempt.label === "public-r2") {
6101
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] public-r2 fetch error: ${err?.message ?? err}, falling back to cloud`);
6102
- continue;
6103
- }
6104
- return c.json({
6105
- success: false,
6106
- error: { code: "cloud_fetch_failed", message: err?.message ?? String(err) }
6107
- }, 502);
6108
- }
6109
- }
6110
- if (!payload) {
6111
- return c.json({
6112
- success: false,
6113
- error: { code: "cloud_fetch_failed", message: `Cloud returned ${lastErrStatus}: ${lastErrText}` }
6114
- }, lastErrStatus === 404 ? 404 : 502);
6115
- }
6116
- const data = payload?.data ?? payload;
6117
- manifest = data?.manifest;
6118
- resolvedVersionId = String(data?.version_id ?? versionId);
6119
- version = String(data?.version ?? "unknown");
6120
- }
6121
- const manifestId = String(manifest?.id ?? manifest?.name ?? "");
6122
- if (!manifest || !manifestId) {
6123
- return c.json({ success: false, error: { code: "invalid_manifest", message: "Invalid manifest payload." } }, inlineManifest ? 400 : 502);
6124
- }
6125
- const conflict = this.findConflict(ctx, manifestId);
6126
- if (conflict === "user-code") {
6127
- return c.json({
6128
- success: false,
6129
- error: {
6130
- code: "manifest_conflict",
6131
- message: `manifest_id "${manifestId}" is already defined by this runtime's local code. Refusing to overwrite. Uninstall the local definition first.`
6132
- }
6133
- }, 409);
6134
- }
6135
- try {
6136
- const manifestService = ctx.getService("manifest");
6137
- manifestService.register(manifest);
6138
- } catch (err) {
6139
- if (inlineManifest) {
6140
- return c.json({
6141
- success: false,
6142
- error: { code: "register_failed", message: `Failed to register imported manifest: ${err?.message ?? err}` }
6143
- }, 422);
6144
- }
6145
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] hot-register failed for ${manifestId} (will load on next restart): ${err?.message ?? err}`);
6146
- }
6147
- const entry = {
6148
- packageId,
6149
- versionId: resolvedVersionId,
6150
- manifestId,
6151
- version,
6152
- manifest,
6153
- installedAt: (/* @__PURE__ */ new Date()).toISOString(),
6154
- installedBy: userId,
6155
- withSampleData: false
6156
- };
6157
- try {
6158
- mkdirSync4(this.storageDir, { recursive: true });
6159
- writeFileSync3(join2(this.storageDir, safeFilename(manifestId)), JSON.stringify(entry, null, 2), "utf8");
6160
- } catch (err) {
6161
- return c.json({
6162
- success: false,
6163
- error: { code: "storage_failed", message: `Failed to persist manifest: ${err?.message ?? err}` }
6164
- }, 500);
6165
- }
6166
- try {
6167
- const ql = ctx.getService("objectql");
6168
- if (ql && typeof ql.syncSchemas === "function") {
6169
- await ql.syncSchemas();
6170
- ctx.logger?.info?.(`[MarketplaceInstallLocal] syncSchemas() ran after registering ${manifestId}`);
6171
- }
6172
- } catch (err) {
6173
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] syncSchemas failed for ${manifestId}: ${err?.message ?? err}`);
6174
- }
6175
- const seededSummary = await this.applySideEffects(ctx, manifest, { seedNow: true, c });
6176
- if (seededSummary.seeded.mode === "inline" && (seededSummary.seeded.inserted ?? 0) + (seededSummary.seeded.updated ?? 0) > 0) {
6177
- entry.withSampleData = true;
6178
- try {
6179
- writeFileSync3(join2(this.storageDir, safeFilename(manifestId)), JSON.stringify(entry, null, 2), "utf8");
6180
- } catch {
6181
- }
6182
- }
6183
- return c.json({
6184
- success: true,
6185
- data: {
6186
- manifestId,
6187
- version,
6188
- versionId: resolvedVersionId,
6189
- installedAt: entry.installedAt,
6190
- hotLoaded: true,
6191
- upgradedFrom: conflict === "marketplace" ? "previous-marketplace-version" : null,
6192
- translationsLoaded: seededSummary.translationsLoaded,
6193
- seeded: seededSummary.seeded,
6194
- note: "App is now available in this runtime. Refresh the console to see it in the app switcher."
6195
- }
6196
- }, 200);
6197
- };
6198
- this.handleList = async (c) => {
6199
- const entries = this.readAll();
6200
- return c.json({
6201
- success: true,
6202
- data: {
6203
- items: entries.map((e) => ({
6204
- packageId: e.packageId,
6205
- versionId: e.versionId,
6206
- manifestId: e.manifestId,
6207
- version: e.version,
6208
- installedAt: e.installedAt,
6209
- installedBy: e.installedBy,
6210
- withSampleData: e.withSampleData ?? false
6211
- })),
6212
- total: entries.length,
6213
- storageDir: this.storageDir
6214
- }
6215
- }, 200);
6216
- };
6217
- this.handleUninstall = async (c, ctx) => {
6218
- const userId = await this.requireAuthenticatedUser(c, ctx);
6219
- if (!userId) {
6220
- return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required." } }, 401);
6221
- }
6222
- const manifestId = String(c.req.param?.("manifestId") ?? c.req.params?.manifestId ?? "").trim();
6223
- if (!manifestId) {
6224
- return c.json({ success: false, error: { code: "bad_request", message: "manifestId path param required." } }, 400);
6225
- }
6226
- const file = join2(this.storageDir, safeFilename(manifestId));
6227
- if (!existsSync3(file)) {
6228
- return c.json({ success: false, error: { code: "not_found", message: `No marketplace install for ${manifestId}.` } }, 404);
6229
- }
6230
- try {
6231
- unlinkSync(file);
6232
- } catch (err) {
6233
- return c.json({ success: false, error: { code: "storage_failed", message: err?.message ?? String(err) } }, 500);
6234
- }
6235
- ctx.logger?.info?.(`[MarketplaceInstallLocal] uninstalled ${manifestId} (cached manifest removed; restart runtime to unload from running kernel)`);
6236
- return c.json({
6237
- success: true,
6238
- data: {
6239
- manifestId,
6240
- note: "Cached manifest removed. The app remains loaded in the running kernel until the next restart (the kernel API does not support unregistering apps in-place)."
6241
- }
6242
- }, 200);
6243
- };
6244
- /**
6245
- * Detect whether `manifestId` is already known to the kernel and classify
6246
- * the source so we can refuse vs upgrade gracefully.
6247
- *
6248
- * 'none' — fresh install
6249
- * 'marketplace' — previously installed by this plugin (allow upgrade)
6250
- * 'user-code' — defined by AppPlugin from objectstack.config.ts
6251
- * (refuse to avoid silently overwriting authored code)
6252
- */
6253
- this.findConflict = (ctx, manifestId) => {
6254
- if (existsSync3(join2(this.storageDir, safeFilename(manifestId)))) {
6255
- return "marketplace";
6256
- }
6257
- try {
6258
- const ql = ctx.getService("objectql");
6259
- const packages = ql?.registry?.getAllPackages?.() ?? [];
6260
- const hit = packages.find(
6261
- (p) => (p?.manifest?.id ?? p?.id ?? p?.manifest?.name) === manifestId
6262
- );
6263
- if (hit) return "user-code";
6264
- } catch {
6265
- }
6266
- return "none";
6267
- };
6268
- /**
6269
- * Pull a userId out of the request's better-auth session, if any.
6270
- * Returns null when there is no signed-in user. v1 does not check
6271
- * admin role — UI gating + the auth requirement is sufficient for
6272
- * dev / single-tenant runtimes. Stricter checks can be layered on
6273
- * via a middleware in cloud-hosted multi-tenant deployments.
6274
- */
6275
- /**
6276
- * POST /api/v1/marketplace/install-local/:manifestId/reseed-sample-data
6277
- *
6278
- * Re-runs SeedLoaderService against the cached manifest's `data` arrays.
6279
- * Idempotent (upsert by id). Useful when:
6280
- * • The user installed an app and skipped sample data
6281
- * • A purge was undone
6282
- * • The user wants a clean baseline back after editing demo rows
6283
- *
6284
- * Multi-tenant: requires an active organization on the session (same
6285
- * rule as install seed path).
6286
- */
6287
- this.handleReseed = async (c, ctx) => {
6288
- const userId = await this.requireAuthenticatedUser(c, ctx);
6289
- if (!userId) {
6290
- return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required." } }, 401);
6291
- }
6292
- const manifestId = String(c.req.param?.("manifestId") ?? c.req.params?.manifestId ?? "").trim();
6293
- if (!manifestId) {
6294
- return c.json({ success: false, error: { code: "bad_request", message: "manifestId path param required." } }, 400);
6295
- }
6296
- const file = join2(this.storageDir, safeFilename(manifestId));
6297
- if (!existsSync3(file)) {
6298
- return c.json({ success: false, error: { code: "not_found", message: `No marketplace install for ${manifestId}.` } }, 404);
6299
- }
6300
- let entry;
6301
- try {
6302
- entry = JSON.parse(readFileSync2(file, "utf8"));
6303
- } catch (err) {
6304
- return c.json({ success: false, error: { code: "storage_failed", message: `Failed to read manifest cache: ${err?.message ?? err}` } }, 500);
6305
- }
6306
- const summary = await this.applySideEffects(ctx, entry.manifest, { seedNow: true, c });
6307
- if (summary.seeded.mode === "skipped") {
6308
- return c.json({
6309
- success: false,
6310
- error: {
6311
- code: "reseed_skipped",
6312
- message: `Reseed did not run: ${summary.seeded.reason ?? "unknown reason"}`
6313
- }
6314
- }, 400);
6315
- }
6316
- try {
6317
- entry.withSampleData = true;
6318
- writeFileSync3(file, JSON.stringify(entry, null, 2), "utf8");
6319
- } catch {
6320
- }
6321
- return c.json({
6322
- success: true,
6323
- data: {
6324
- manifestId,
6325
- inserted: summary.seeded.inserted ?? 0,
6326
- updated: summary.seeded.updated ?? 0,
6327
- errors: summary.seeded.errors ?? 0,
6328
- withSampleData: true
6329
- }
6330
- }, 200);
6331
- };
6332
- /**
6333
- * POST /api/v1/marketplace/install-local/:manifestId/purge-sample-data
6334
- *
6335
- * Deletes every record whose id is declared in the cached manifest's
6336
- * seed datasets. Uses the `driver` service directly to bypass ACL /
6337
- * lifecycle hooks (same pattern as cloud purge). User-created records
6338
- * are never touched — only ids declared in the package's bundled
6339
- * datasets are removed. Already-deleted rows count as `skipped`.
6340
- */
6341
- this.handlePurge = async (c, ctx) => {
6342
- const userId = await this.requireAuthenticatedUser(c, ctx);
6343
- if (!userId) {
6344
- return c.json({ success: false, error: { code: "unauthorized", message: "Authentication required." } }, 401);
6345
- }
6346
- const manifestId = String(c.req.param?.("manifestId") ?? c.req.params?.manifestId ?? "").trim();
6347
- if (!manifestId) {
6348
- return c.json({ success: false, error: { code: "bad_request", message: "manifestId path param required." } }, 400);
6349
- }
6350
- const file = join2(this.storageDir, safeFilename(manifestId));
6351
- if (!existsSync3(file)) {
6352
- return c.json({ success: false, error: { code: "not_found", message: `No marketplace install for ${manifestId}.` } }, 404);
6353
- }
6354
- let entry;
6355
- try {
6356
- entry = JSON.parse(readFileSync2(file, "utf8"));
6357
- } catch (err) {
6358
- return c.json({ success: false, error: { code: "storage_failed", message: `Failed to read manifest cache: ${err?.message ?? err}` } }, 500);
6359
- }
6360
- const datasets = Array.isArray(entry.manifest?.data) ? entry.manifest.data.filter((d) => d && d.object && Array.isArray(d.records)) : [];
6361
- if (datasets.length === 0) {
6362
- return c.json({
6363
- success: false,
6364
- error: { code: "nothing_to_purge", message: "This package declares no seed datasets." }
6365
- }, 400);
6366
- }
6367
- let driver;
6368
- try {
6369
- driver = ctx.getService("driver");
6370
- } catch {
6371
- }
6372
- if (!driver || typeof driver.delete !== "function") {
6373
- return c.json({
6374
- success: false,
6375
- error: { code: "driver_missing", message: "driver service unavailable \u2014 cannot purge." }
6376
- }, 500);
6377
- }
6378
- let deleted = 0;
6379
- let skipped = 0;
6380
- let errors = 0;
6381
- for (const ds of datasets) {
6382
- const object = String(ds.object);
6383
- for (const rec of ds.records) {
6384
- const id = rec?.id;
6385
- if (id === void 0 || id === null || id === "") {
6386
- skipped++;
6387
- continue;
6388
- }
6389
- try {
6390
- const r = await driver.delete(object, id);
6391
- if (r === false || r === 0 || r?.deleted === 0) skipped++;
6392
- else deleted++;
6393
- } catch (err) {
6394
- const msg = String(err?.message ?? err);
6395
- if (/not.?found|no row/i.test(msg)) skipped++;
6396
- else {
6397
- errors++;
6398
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] purge ${object}#${id}: ${msg}`);
6399
- }
6400
- }
6401
- }
6402
- }
6403
- try {
6404
- entry.withSampleData = false;
6405
- writeFileSync3(file, JSON.stringify(entry, null, 2), "utf8");
6406
- } catch {
6407
- }
6408
- ctx.logger?.info?.(`[MarketplaceInstallLocal] purged ${manifestId}: deleted=${deleted} skipped=${skipped} errors=${errors}`);
6409
- return c.json({
6410
- success: true,
6411
- data: { manifestId, deleted, skipped, errors, withSampleData: false }
6412
- }, 200);
6413
- };
6414
- /**
6415
- * Replicate the start-time side-effects that AppPlugin runs for
6416
- * statically-declared apps but the `manifest` service does NOT:
6417
- *
6418
- * 1. Load `manifest.translations` (array of `Record<locale, data>`)
6419
- * into the i18n service — auto-creating an in-memory fallback if
6420
- * none is registered, matching AppPlugin's behaviour.
6421
- *
6422
- * 2. Merge `manifest.data` (an array of seed datasets) into the
6423
- * kernel's `seed-datasets` service so SecurityPlugin's per-org
6424
- * replay middleware picks them up on every future
6425
- * sys_organization insert.
6426
- *
6427
- * 3. When `seedNow=true`, also run the seed immediately so the user
6428
- * sees demo data without having to create a new org:
6429
- * • single-tenant: run SeedLoaderService inline (mirrors
6430
- * AppPlugin single-tenant branch)
6431
- * • multi-tenant: invoke `seed-replayer` for the caller's
6432
- * active org (resolved from the request session)
6433
- *
6434
- * Errors are logged but never thrown — install succeeds even if
6435
- * post-register side-effects partially fail (the manifest itself is
6436
- * already registered + cached). Returns a small summary for the
6437
- * response envelope.
6438
- */
6439
- this.applySideEffects = async (ctx, manifest, opts) => {
6440
- const appId = String(manifest?.id ?? "unknown");
6441
- let translationsLoaded = 0;
6442
- let seedSummary = { mode: "skipped", reason: "no-datasets" };
6443
- try {
6444
- const bundles = [];
6445
- if (Array.isArray(manifest?.translations)) bundles.push(...manifest.translations);
6446
- if (Array.isArray(manifest?.i18n)) bundles.push(...manifest.i18n);
6447
- if (bundles.length > 0) {
6448
- let i18nService;
6449
- try {
6450
- i18nService = ctx.getService("i18n");
6451
- } catch {
6452
- }
6453
- if (!i18nService) {
6454
- try {
6455
- const mod = await import("@objectstack/core");
6456
- const createMemoryI18n = mod.createMemoryI18n;
6457
- if (typeof createMemoryI18n === "function") {
6458
- i18nService = createMemoryI18n();
6459
- ctx.registerService?.("i18n", i18nService);
6460
- ctx.logger?.info?.(`[MarketplaceInstallLocal] auto-registered in-memory i18n fallback for "${appId}"`);
6461
- }
6462
- } catch {
6463
- }
6464
- }
6465
- if (i18nService?.loadTranslations) {
6466
- for (const bundle of bundles) {
6467
- for (const [locale, data] of Object.entries(bundle)) {
6468
- if (data && typeof data === "object") {
6469
- try {
6470
- i18nService.loadTranslations(locale, data);
6471
- translationsLoaded++;
6472
- } catch (err) {
6473
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to load ${appId} translations for ${locale}: ${err?.message ?? err}`);
6474
- }
6475
- }
6476
- }
6477
- }
6478
- ctx.logger?.info?.(`[MarketplaceInstallLocal] loaded ${translationsLoaded} locale bundle(s) for ${appId}`);
6479
- }
6480
- }
6481
- } catch (err) {
6482
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] i18n side-effect failed for ${appId}: ${err?.message ?? err}`);
6483
- }
6484
- const datasets = Array.isArray(manifest?.data) ? manifest.data.filter((d) => d && d.object && Array.isArray(d.records)) : [];
6485
- if (datasets.length > 0) {
6486
- try {
6487
- const kernel = ctx.kernel;
6488
- let existing = [];
6489
- try {
6490
- const v = kernel?.getService?.("seed-datasets");
6491
- if (Array.isArray(v)) existing = v;
6492
- } catch {
6493
- }
6494
- const merged = [...existing, ...datasets];
6495
- if (kernel?.registerService) kernel.registerService("seed-datasets", merged);
6496
- else ctx.registerService?.("seed-datasets", merged);
6497
- ctx.logger?.info?.(`[MarketplaceInstallLocal] merged ${datasets.length} seed dataset(s) into kernel (total: ${merged.length})`);
6498
- } catch (err) {
6499
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] failed to merge seed-datasets: ${err?.message ?? err}`);
6500
- }
6501
- }
6502
- if (opts.seedNow && datasets.length > 0) {
6503
- const multiTenant = String(readEnvWithDeprecation3("OS_MULTI_ORG_ENABLED", "OS_MULTI_TENANT") ?? "false").toLowerCase() !== "false";
6504
- try {
6505
- const ql = ctx.getService("objectql");
6506
- let metadata;
6507
- try {
6508
- metadata = ctx.getService("metadata");
6509
- } catch {
6510
- }
6511
- if (!ql || !metadata) {
6512
- seedSummary = { mode: "skipped", reason: "objectql-or-metadata-missing" };
6513
- } else {
6514
- let organizationId;
6515
- if (multiTenant) {
6516
- const resolved = await this.resolveActiveOrgId(opts.c, ctx);
6517
- if (resolved) organizationId = resolved;
6518
- else {
6519
- seedSummary = { mode: "skipped", reason: "multi-tenant-no-active-org" };
6520
- ctx.logger?.warn?.("[MarketplaceInstallLocal] multi-tenant: no active org on request \u2014 data not seeded");
6521
- }
6522
- }
6523
- if (!multiTenant || organizationId) {
6524
- const [{ SeedLoaderService: SeedLoaderService2 }, { SeedLoaderRequestSchema }] = await Promise.all([
6525
- Promise.resolve().then(() => (init_seed_loader(), seed_loader_exports)),
6526
- import("@objectstack/spec/data")
6527
- ]);
6528
- const seedLoader = new SeedLoaderService2(ql, metadata, ctx.logger);
6529
- const request = SeedLoaderRequestSchema.parse({
6530
- datasets,
6531
- config: {
6532
- defaultMode: "upsert",
6533
- multiPass: true,
6534
- ...organizationId ? { organizationId } : {}
6535
- }
6536
- });
6537
- const result = await seedLoader.load(request);
6538
- seedSummary = {
6539
- mode: "inline",
6540
- inserted: result.summary.totalInserted,
6541
- updated: result.summary.totalUpdated,
6542
- errors: result.errors.length
6543
- };
6544
- ctx.logger?.info?.(`[MarketplaceInstallLocal] inline seed for ${appId}${organizationId ? ` (org=${organizationId})` : ""}: inserted=${seedSummary.inserted} updated=${seedSummary.updated} errors=${seedSummary.errors}`);
6545
- }
6546
- }
6547
- } catch (err) {
6548
- seedSummary = { mode: "skipped", reason: `seed-error: ${err?.message ?? err}` };
6549
- ctx.logger?.warn?.(`[MarketplaceInstallLocal] seed run failed for ${appId}: ${err?.message ?? err}`);
6550
- }
6551
- }
6552
- return { translationsLoaded, seeded: seedSummary };
6553
- };
6554
- /**
6555
- * Best-effort active-org resolution. Reads the better-auth session
6556
- * (same path as requireAuthenticatedUser) and returns
6557
- * `session.activeOrganizationId`, falling back to the user's first
6558
- * org membership.
6559
- */
6560
- this.resolveActiveOrgId = async (c, ctx) => {
6561
- if (!c?.req?.raw?.headers) return null;
6562
- try {
6563
- const authService = ctx.getService("auth");
6564
- let api = authService?.api;
6565
- if (!api && typeof authService?.getApi === "function") api = await authService.getApi();
6566
- if (!api?.getSession) return null;
6567
- const session = await api.getSession({ headers: c.req.raw.headers });
6568
- const direct = session?.session?.activeOrganizationId ?? session?.activeOrganizationId ?? null;
6569
- if (direct) return String(direct);
6570
- const userId = session?.user?.id;
6571
- if (!userId) return null;
6572
- try {
6573
- const ql = ctx.getService("objectql");
6574
- if (ql?.find) {
6575
- const rows = await ql.find("sys_organization_member", { where: { user_id: userId }, limit: 1, context: { isSystem: true } });
6576
- const row = Array.isArray(rows) ? rows[0] : rows?.items?.[0] ?? null;
6577
- return row?.organization_id ? String(row.organization_id) : null;
6578
- }
6579
- } catch {
6580
- }
6581
- } catch {
6582
- }
6583
- return null;
6584
- };
6585
- this.requireAuthenticatedUser = async (c, ctx) => {
6586
- try {
6587
- const authService = ctx.getService("auth");
6588
- let api = authService?.api;
6589
- if (!api && typeof authService?.getApi === "function") {
6590
- api = await authService.getApi();
6591
- }
6592
- if (api?.getSession && c?.req?.raw?.headers) {
6593
- const session = await api.getSession({ headers: c.req.raw.headers });
6594
- const userId = session?.user?.id ?? null;
6595
- if (userId) return String(userId);
6596
- }
6597
- } catch {
6598
- }
6599
- const xUserId = c?.req?.header?.("x-user-id");
6600
- if (xUserId) return String(xUserId);
6601
- return null;
6602
- };
6603
- this.readAll = () => {
6604
- if (!existsSync3(this.storageDir)) return [];
6605
- const out = [];
6606
- for (const name of readdirSync(this.storageDir)) {
6607
- if (!name.endsWith(".json")) continue;
6608
- try {
6609
- const raw = readFileSync2(join2(this.storageDir, name), "utf8");
6610
- out.push(JSON.parse(raw));
6611
- } catch {
6612
- }
6613
- }
6614
- return out;
6615
- };
6616
- this.cloudUrl = resolveCloudUrl(config.controlPlaneUrl);
6617
- this.storageDir = config.storageDir ? resolve(config.storageDir) : resolve(process.cwd(), DEFAULT_DIR);
6618
- }
6619
- };
6620
-
6621
- // src/cloud/runtime-config-plugin.ts
6622
- var RuntimeConfigPlugin = class {
6623
- constructor(config = {}) {
6624
- this.name = "com.objectstack.runtime.runtime-config";
6625
- this.version = "1.0.0";
6626
- this.init = async (_ctx) => {
6627
- };
6628
- this.start = async (ctx) => {
6629
- ctx.hook("kernel:ready", async () => {
6630
- let httpServer;
6631
- try {
6632
- httpServer = ctx.getService("http-server");
6633
- } catch {
6634
- ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server not available \u2014 runtime/config not mounted");
6635
- return;
6636
- }
6637
- if (!httpServer || typeof httpServer.getRawApp !== "function") {
6638
- ctx.logger?.warn?.("[RuntimeConfigPlugin] http-server missing getRawApp() \u2014 runtime/config not mounted");
6639
- return;
6640
- }
6641
- const rawApp = httpServer.getRawApp();
6642
- const features = {
6643
- installLocal: this.installLocal,
6644
- marketplace: true,
6645
- aiStudio: this.aiStudio
6646
- };
6647
- let envRegistry = null;
6648
- try {
6649
- envRegistry = ctx.getService("env-registry");
6650
- } catch {
6651
- }
6652
- const handler = async (c) => {
6653
- const rawHost = c.req.header("host") ?? "";
6654
- const host = rawHost.split(":")[0].toLowerCase().trim();
6655
- let defaultEnvironmentId;
6656
- let defaultOrgId;
6657
- let resolvedSingleEnv = this.singleEnvironment;
6658
- const resolveFn = typeof envRegistry?.resolveByHostname === "function" ? envRegistry.resolveByHostname.bind(envRegistry) : typeof envRegistry?.resolveHostname === "function" ? envRegistry.resolveHostname.bind(envRegistry) : null;
6659
- if (resolveFn && host) {
6660
- try {
6661
- const resolved = await resolveFn(host);
6662
- if (resolved?.environmentId) {
6663
- defaultEnvironmentId = String(resolved.environmentId);
6664
- const orgId = resolved.organizationId ?? resolved.organization_id;
6665
- if (orgId) defaultOrgId = String(orgId);
6666
- resolvedSingleEnv = true;
6667
- }
6668
- } catch {
6669
- }
6670
- }
6671
- return c.json({
6672
- cloudUrl: this.cloudUrl,
6673
- singleEnvironment: resolvedSingleEnv,
6674
- defaultOrgId,
6675
- defaultEnvironmentId,
6676
- features,
6677
- branding: {
6678
- productName: this.productName,
6679
- productShortName: this.productShortName
6680
- }
6681
- });
6682
- };
6683
- rawApp.get("/api/v1/runtime/config", handler);
6684
- rawApp.get("/api/v1/studio/runtime-config", handler);
6685
- ctx.logger?.info?.("[RuntimeConfigPlugin] mounted /api/v1/runtime/config", {
6686
- cloudUrl: this.cloudUrl || "(empty)",
6687
- installLocal: this.installLocal,
6688
- perHostEnvResolution: !!envRegistry
6689
- });
6690
- });
6691
- };
6692
- this.destroy = async () => {
6693
- };
6694
- this.cloudUrl = config.controlPlaneUrl === "" ? "" : resolveCloudUrl(config.controlPlaneUrl) ?? "";
6695
- this.installLocal = !!config.installLocal;
6696
- this.aiStudio = config.aiStudio !== false;
6697
- this.singleEnvironment = !!config.singleEnvironment;
6698
- const envName = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_NAME : void 0)?.trim();
6699
- const envShort = (typeof process !== "undefined" ? process.env?.OS_PRODUCT_SHORT_NAME : void 0)?.trim();
6700
- this.productName = (config.productName ?? envName ?? "ObjectOS").trim() || "ObjectOS";
6701
- this.productShortName = (config.productShortName ?? envShort ?? this.productName).trim() || this.productName;
6702
- }
6703
- };
6704
-
6705
5518
  // src/sandbox/script-runner.ts
6706
5519
  var UnimplementedScriptRunner = class {
6707
5520
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -6732,10 +5545,9 @@ import {
6732
5545
  createRestApiPlugin
6733
5546
  } from "@objectstack/rest";
6734
5547
  export * from "@objectstack/core";
6735
- import { readEnvWithDeprecation as readEnvWithDeprecation4, _resetEnvDeprecationWarnings } from "@objectstack/types";
5548
+ import { readEnvWithDeprecation as readEnvWithDeprecation3, _resetEnvDeprecationWarnings } from "@objectstack/types";
6736
5549
  export {
6737
5550
  AppPlugin,
6738
- DEFAULT_CLOUD_URL,
6739
5551
  DEFAULT_RATE_LIMITS,
6740
5552
  DriverPlugin,
6741
5553
  ExternalValidationPlugin,
@@ -6743,8 +5555,6 @@ export {
6743
5555
  HttpServer,
6744
5556
  InMemoryErrorReporter,
6745
5557
  InMemoryMetricsRegistry,
6746
- MarketplaceInstallLocalPlugin,
6747
- MarketplaceProxyPlugin,
6748
5558
  MiddlewareManager,
6749
5559
  NoopErrorReporter,
6750
5560
  NoopMetricsRegistry,
@@ -6759,7 +5569,6 @@ export {
6759
5569
  RouteGroupBuilder,
6760
5570
  RouteManager,
6761
5571
  Runtime,
6762
- RuntimeConfigPlugin,
6763
5572
  SYSTEM_ENVIRONMENT_ID,
6764
5573
  SandboxError,
6765
5574
  SeedLoaderService,
@@ -6785,8 +5594,7 @@ export {
6785
5594
  mergeRuntimeModule,
6786
5595
  parseTraceparent,
6787
5596
  readArtifactSource,
6788
- readEnvWithDeprecation4 as readEnvWithDeprecation,
6789
- resolveCloudUrl,
5597
+ readEnvWithDeprecation3 as readEnvWithDeprecation,
6790
5598
  resolveDefaultArtifactPath,
6791
5599
  resolveErrorReporter,
6792
5600
  resolveMetrics,