@lensmcp/cluster 1.26.2 → 1.26.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-host.js +1 -1
- package/devserver-host.d.ts +5 -0
- package/devserver-host.js +1 -1
- package/executors/gateway/runtime/auth.js +1 -1
- package/executors/gateway/runtime/control.d.ts +25 -0
- package/executors/gateway/runtime/control.js +2 -2
- package/executors/gateway/runtime/discovery.js +1 -1
- package/executors/gateway/runtime/docker-sweep.d.ts +51 -0
- package/executors/gateway/runtime/docker-sweep.js +1 -0
- package/executors/gateway/runtime/edge.d.ts +2 -0
- package/executors/gateway/runtime/edge.js +1 -1
- package/executors/gateway/runtime/frontend-updates.d.ts +24 -0
- package/executors/gateway/runtime/frontend-updates.js +1 -0
- package/executors/gateway/runtime/handler.js +1 -1
- package/executors/gateway/runtime/legacy-dashboard-link.d.ts +10 -0
- package/executors/gateway/runtime/legacy-dashboard-link.js +1 -0
- package/executors/gateway/runtime/lens-children.d.ts +9 -0
- package/executors/gateway/runtime/lens-children.js +1 -1
- package/executors/gateway/runtime/lifecycle.d.ts +2 -0
- package/executors/gateway/runtime/lifecycle.js +4 -4
- package/executors/gateway/runtime/peer-hub.d.ts +54 -0
- package/executors/gateway/runtime/peer-hub.js +1 -0
- package/executors/gateway/runtime/proxy.js +1 -1
- package/executors/gateway/runtime/remote-instances.d.ts +167 -0
- package/executors/gateway/runtime/remote-instances.js +1 -0
- package/executors/gateway/runtime/run-routes.d.ts +186 -0
- package/executors/gateway/runtime/run-routes.js +1 -0
- package/executors/gateway/runtime/server.js +2 -2
- package/executors/gateway/runtime/service-updates.d.ts +44 -0
- package/executors/gateway/runtime/service-updates.js +1 -0
- package/executors/gateway/runtime/services-decl.d.ts +2 -0
- package/executors/gateway/runtime/services-decl.js +1 -1
- package/executors/gateway/runtime/shared-build.d.ts +8 -1
- package/executors/gateway/runtime/shared-build.js +4 -4
- package/executors/gateway/runtime/types.d.ts +54 -0
- package/executors/gateway/runtime/update-wiring.d.ts +57 -0
- package/executors/gateway/runtime/update-wiring.js +2 -0
- package/executors/gateway/runtime/updates.d.ts +148 -0
- package/executors/gateway/runtime/updates.js +1 -0
- package/executors/gateway/runtime/upgrade.js +1 -1
- package/executors/serve/serve.impl.js +1 -1
- package/executors/serve/updates-gate.d.ts +147 -0
- package/executors/serve/updates-gate.js +2 -0
- package/executors/trust/trust.impl.js +3 -3
- package/main.devserver.js +10 -10
- package/package.json +5 -5
- package/program-id.d.ts +4 -0
- package/program-id.js +1 -0
- package/shared-build/host.d.ts +102 -2
- package/shared-build/host.js +3 -3
- package/shared-build/protocol.d.ts +59 -3
- package/shared-build/protocol.js +1 -1
- package/shared-build/shared-compilation.d.ts +21 -0
- package/shared-build/shared-compilation.js +3 -3
- package/static-checks-record.d.ts +391 -0
- package/static-checks-record.js +5 -0
- package/tsgo-check-plugin.d.ts +107 -43
- package/tsgo-check-plugin.js +4 -5
- package/tsgo-shim.d.ts +112 -0
- package/tsgo-shim.js +2 -0
- package/typecheck-bus.d.ts +36 -5
- package/typecheck-bus.js +4 -4
- package/typecheck-memory.d.ts +187 -0
- package/typecheck-memory.js +1 -0
- package/typecheck-queue.d.ts +41 -3
- package/typecheck-queue.js +1 -1
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* UPDATE MODES (planning/updates/00-plan.md, U2): whether a checkout's services and frontends take every save live, hold
|
|
3
|
+
* what is saved until someone asks, or do not run at all — and the HOLDS that let many agents edit one checkout without
|
|
4
|
+
* a build per save.
|
|
5
|
+
*
|
|
6
|
+
* The owner, 2026-11-14: «if we have many agents working, each one can pause hmr and can access the services but not up
|
|
7
|
+
* to date, and when they finished the work it will trigger build. This way we will reduce the CPU, but this feature can be
|
|
8
|
+
* toggled, like hmr, manual, off (parked).»
|
|
9
|
+
*
|
|
10
|
+
* - A piece (a service or a frontend of one workspace) has a MODE: the checkout's override (`.lensmcp/updates.json`,
|
|
11
|
+
* the person's — CLI and Cluster tab) ?? its declaration's (`lensmcp.json → services.<name>.updates`) ?? `hmr`.
|
|
12
|
+
* - A HOLD is one holder's «don't build yet» — an agent's, taken by its hooks before an edit (UM-D2), renewed by its
|
|
13
|
+
* calls, ended by its turn's end, its session's end or its lease lapsing (UM-D4). Holds are counted per holder: one
|
|
14
|
+
* release never ends another's.
|
|
15
|
+
* - The EFFECTIVE state follows: `parked` (mode off) · `manual` (mode manual) · `held` (mode hmr, held) · `live`.
|
|
16
|
+
* Every change of it drives the piece's GATE — the runner's or the build host's compile, a Vite's pushes (U1, U3):
|
|
17
|
+
* live → not live suspends; back to live resumes what was collected; parked stops and starts.
|
|
18
|
+
* - The LAST release updates (UM-D3): a piece left `manual` by the release of its last hold gets one update too — an
|
|
19
|
+
* agent finishing is a request. An explicit update applies at once, whatever holds.
|
|
20
|
+
*
|
|
21
|
+
* Everything that touches a process is behind {@link UpdateGates}; this module only decides, in order, per piece.
|
|
22
|
+
*/
|
|
23
|
+
export type UpdateMode = 'hmr' | 'manual' | 'off';
|
|
24
|
+
export type UpdateState = 'live' | 'held' | 'manual' | 'parked';
|
|
25
|
+
export type PieceKind = 'service' | 'frontend';
|
|
26
|
+
export declare const UPDATE_MODES: readonly UpdateMode[];
|
|
27
|
+
export declare function isUpdateMode(v: unknown): v is UpdateMode;
|
|
28
|
+
/** One workspace's piece, as the gateway knows it. */
|
|
29
|
+
export interface PieceRef {
|
|
30
|
+
workspace: string;
|
|
31
|
+
piece: string;
|
|
32
|
+
kind: PieceKind;
|
|
33
|
+
}
|
|
34
|
+
export interface UpdateHolder {
|
|
35
|
+
/** `claude`, `codex`, `cli`, `dashboard`, … */
|
|
36
|
+
client: string;
|
|
37
|
+
/** The holder's session — the key that counts holds apart. */
|
|
38
|
+
session: string;
|
|
39
|
+
/** A name a person reads: the agent's, the goal's. */
|
|
40
|
+
name?: string;
|
|
41
|
+
}
|
|
42
|
+
export interface UpdateHold {
|
|
43
|
+
holder: UpdateHolder;
|
|
44
|
+
/** `*`: every piece of the workspace (an automatic hold, UM-D7). */
|
|
45
|
+
pieces: '*' | string[];
|
|
46
|
+
since: number;
|
|
47
|
+
until: number;
|
|
48
|
+
why?: string;
|
|
49
|
+
}
|
|
50
|
+
/** What a held piece's gate collected: the files saved since its hold, and the compiles (or pushes) it spared. */
|
|
51
|
+
export interface Collected {
|
|
52
|
+
files: string[];
|
|
53
|
+
/** Unknown for a piece whose saves its gate cannot see (a build host's project out of a live group). */
|
|
54
|
+
count?: number;
|
|
55
|
+
skipped: number;
|
|
56
|
+
since: number;
|
|
57
|
+
}
|
|
58
|
+
export type UpdateOutcomeKind = 'swapped' | 'unchanged' | 'failed' | 'skipped' | 'pending';
|
|
59
|
+
export interface UpdateOutcome {
|
|
60
|
+
piece: string;
|
|
61
|
+
outcome: UpdateOutcomeKind;
|
|
62
|
+
ms: number;
|
|
63
|
+
errors?: string[];
|
|
64
|
+
/** Why `skipped` or `pending`. */
|
|
65
|
+
why?: string;
|
|
66
|
+
}
|
|
67
|
+
/** The processes behind the pieces: each call is for one piece and settles once its gate has done it. */
|
|
68
|
+
export interface UpdateGates {
|
|
69
|
+
/** Stop compiling (pushing) what is saved; collect it. */
|
|
70
|
+
hold(ref: PieceRef): Promise<void>;
|
|
71
|
+
/** Back to live: what was collected is built and applied once. */
|
|
72
|
+
release(ref: PieceRef): Promise<UpdateOutcome>;
|
|
73
|
+
/** Build and apply what was collected once, and stay held. */
|
|
74
|
+
update(ref: PieceRef): Promise<UpdateOutcome>;
|
|
75
|
+
/** Stop it; nothing runs. */
|
|
76
|
+
park(ref: PieceRef): Promise<void>;
|
|
77
|
+
/** Start it again — held from its start when `held` (its first build serves the current files, then it holds). */
|
|
78
|
+
unpark(ref: PieceRef, held: boolean): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
export interface UpdatesDeps {
|
|
81
|
+
now(): number;
|
|
82
|
+
/** The workspace's pieces now (its services and frontends); unknown workspace → []. */
|
|
83
|
+
pieces(workspace: string): Array<{
|
|
84
|
+
piece: string;
|
|
85
|
+
kind: PieceKind;
|
|
86
|
+
}>;
|
|
87
|
+
/** The declaration's default mode for a piece (lensmcp.json `services.<name>.updates`). */
|
|
88
|
+
declared(workspace: string, piece: string): UpdateMode | undefined;
|
|
89
|
+
/** The checkout's overrides (`.lensmcp/updates.json`), read when the workspace is first asked about. */
|
|
90
|
+
load(workspace: string): Record<string, UpdateMode>;
|
|
91
|
+
save(workspace: string, modes: Record<string, UpdateMode>): void;
|
|
92
|
+
gates: UpdateGates;
|
|
93
|
+
/** A bus event in the workspace's own bus (`updates-held`, `updates-applied`, `updates-mode`). */
|
|
94
|
+
publish?(workspace: string, kind: string, data: Record<string, unknown>): void;
|
|
95
|
+
log?(line: string): void;
|
|
96
|
+
}
|
|
97
|
+
/** A hold lives as long as its agent's session lease (UM-D4): 15 min after its last renewal. */
|
|
98
|
+
export declare const DEFAULT_HOLD_SEC: number;
|
|
99
|
+
/** The longest hold one call can ask for — as `/awake`'s `MAX_AWAKE_SEC`. */
|
|
100
|
+
export declare const MAX_HOLD_SEC: number;
|
|
101
|
+
export interface PieceStatus {
|
|
102
|
+
piece: string;
|
|
103
|
+
kind: PieceKind;
|
|
104
|
+
mode: UpdateMode;
|
|
105
|
+
/** Where the mode came from. */
|
|
106
|
+
modeFrom: 'checkout' | 'declaration' | 'default';
|
|
107
|
+
state: UpdateState;
|
|
108
|
+
holders: Array<UpdateHolder & {
|
|
109
|
+
since: number;
|
|
110
|
+
until: number;
|
|
111
|
+
why?: string;
|
|
112
|
+
}>;
|
|
113
|
+
collected?: Collected;
|
|
114
|
+
lastUpdate?: UpdateOutcome & {
|
|
115
|
+
at: number;
|
|
116
|
+
by?: string;
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
export interface WorkspaceUpdates {
|
|
120
|
+
workspace: string;
|
|
121
|
+
pieces: PieceStatus[];
|
|
122
|
+
holds: UpdateHold[];
|
|
123
|
+
}
|
|
124
|
+
export interface Updates {
|
|
125
|
+
status(workspace: string): WorkspaceUpdates;
|
|
126
|
+
/** The effective state of one piece — what the sweeps and the spawns read. */
|
|
127
|
+
stateOf(workspace: string, piece: string): UpdateState;
|
|
128
|
+
/** Should a fresh tree or generation of this piece start held? (`LENSMCP_UPDATES_HELD=1`) */
|
|
129
|
+
startsHeld(workspace: string, piece: string): boolean;
|
|
130
|
+
setMode(workspace: string, pieces: string[], mode: UpdateMode, by?: string): Promise<WorkspaceUpdates>;
|
|
131
|
+
/** Take or renew `holder`'s hold. Idempotent per holder; a renewal may widen `pieces`. */
|
|
132
|
+
hold(workspace: string, holder: UpdateHolder, opts?: {
|
|
133
|
+
pieces?: string[];
|
|
134
|
+
ttlSec?: number;
|
|
135
|
+
why?: string;
|
|
136
|
+
}): Promise<UpdateHold>;
|
|
137
|
+
/** End `holder`'s hold. Each piece no longer held is released (or, left manual, updated once). */
|
|
138
|
+
release(workspace: string, holder: Pick<UpdateHolder, 'client' | 'session'>, by?: string): Promise<UpdateOutcome[]>;
|
|
139
|
+
/** Update now: every held or manual piece named (default: all of them), whatever holds. */
|
|
140
|
+
apply(workspace: string, pieces?: string[], by?: string): Promise<UpdateOutcome[]>;
|
|
141
|
+
/** A gate's report of what it collected for a piece. */
|
|
142
|
+
collected(workspace: string, piece: string, c: Omit<Collected, 'since'>): void;
|
|
143
|
+
/** End the holds whose lease lapsed — the gateway's sweep calls it. */
|
|
144
|
+
sweep(): Promise<void>;
|
|
145
|
+
/** Forget a workspace (unregistered). */
|
|
146
|
+
forget(workspace: string): void;
|
|
147
|
+
}
|
|
148
|
+
export declare function createUpdates(deps: UpdatesDeps): Updates;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var D=Object.defineProperty;var k=(a,u)=>D(a,"name",{value:u,configurable:!0});var A=Object.defineProperty,c=k((a,u)=>A(a,"name",{value:u,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_HOLD_SEC=exports.DEFAULT_HOLD_SEC=exports.UPDATE_MODES=void 0,exports.isUpdateMode=isUpdateMode,exports.createUpdates=createUpdates,exports.UPDATE_MODES=["hmr","manual","off"];function isUpdateMode(a){return typeof a=="string"&&exports.UPDATE_MODES.includes(a)}k(isUpdateMode,"isUpdateMode"),c(isUpdateMode,"isUpdateMode"),exports.DEFAULT_HOLD_SEC=900,exports.MAX_HOLD_SEC=14400;const MAX_FILES=50,holderKey=c(a=>`${a.client}:${a.session}`,"holderKey"),covers=c((a,u)=>a.pieces==="*"||a.pieces.includes(u),"covers"),notLive=c(a=>a==="held"||a==="manual","notLive"),owed=c(a=>!!a&&(a.count===void 0||a.count>0||a.files.length>0),"owed");function createUpdates(a){const u=new Map,m=c(e=>{let s=u.get(e);if(!s){let t={};try{t=Object.fromEntries(Object.entries(a.load(e)).filter(([,o])=>isUpdateMode(o)))}catch(o){a.log?.(`[updates] ${e}: its .lensmcp/updates.json could not be read (${o.message}) \u2014 every piece takes its declared mode`)}s={modes:t,holds:new Map,pieces:new Map},u.set(e,s)}return s},"ws"),b=c((e,s)=>{let t=e.pieces.get(s);return t||(t={driven:"live",chain:Promise.resolve()},e.pieces.set(s,t)),t},"memo"),_=c((e,s,t)=>{const o=s.modes[t];if(o)return{mode:o,from:"checkout"};const i=a.declared(e,t);return i&&isUpdateMode(i)?{mode:i,from:"declaration"}:{mode:"hmr",from:"default"}},"modeOf"),O=c(e=>{const s=a.now();return[...e.holds.values()].filter(t=>t.until>s)},"liveHolds"),f=c((e,s,t)=>{const{mode:o}=_(e,s,t);return o==="off"?"parked":o==="manual"?"manual":O(s).some(i=>covers(i,t))?"held":"live"},"stateIn"),E=c((e,s)=>{const t=a.pieces(e).find(o=>o.piece===s);return t?{workspace:e,piece:s,kind:t.kind}:void 0},"refOf"),v=c((e,s,t,o)=>(s.lastUpdate={...t,at:a.now(),...o?{by:o}:{}},(t.outcome==="swapped"||t.outcome==="unchanged")&&(s.collected=void 0),a.publish?.(e,"updates-applied",{piece:t.piece,outcome:t.outcome,ms:t.ms,...t.errors?{errors:t.errors}:{},...o?{by:o}:{}}),t),"record"),U=c((e,s,t={})=>{const o=m(e),i=b(o,s),d=c(async()=>{const n=E(e,s);if(!n)return;const p=i.driven,l=f(e,o,s);if(p===l)return l==="manual"&&t.lastRelease&&owed(i.collected)?v(e,i,await a.gates.update(n),t.by):void 0;if(l==="parked"){await a.gates.park(n),i.driven="parked",i.collected=void 0;return}if(p==="parked"){await a.gates.unpark(n,notLive(l)),i.driven=l,notLive(l)&&(i.collected={files:[],count:0,skipped:0,since:a.now()});return}if(p==="live"&¬Live(l)){await a.gates.hold(n),i.driven=l,i.collected={files:[],count:0,skipped:0,since:a.now()},a.publish?.(e,"updates-held",{piece:s,state:l});return}if(notLive(p)&&l==="live"){const h=await a.gates.release(n);return i.driven="live",v(e,i,h,t.by)}if(i.driven=l,l==="manual"&&t.lastRelease&&owed(i.collected))return v(e,i,await a.gates.update(n),t.by)},"run"),r=i.chain.then(d,d);return i.chain=r.catch(n=>{a.log?.(`[updates] ${e}/${s}: its gate failed (${n?.message??String(n)}) \u2014 left as it was`)}),r},"drive"),y=c(async(e,s,t={})=>(await Promise.all(s.map(o=>U(e,o,t).catch(i=>({piece:o,outcome:"failed",ms:0,errors:[String(i?.message??i)]}))))).filter(o=>!!o),"driveAll"),w=c(e=>a.pieces(e).map(s=>s.piece),"names"),M=c(e=>{const s=m(e),t=O(s);return{workspace:e,holds:t,pieces:a.pieces(e).map(({piece:o,kind:i})=>{const{mode:d,from:r}=_(e,s,o),n=s.pieces.get(o),p=f(e,s,o);return{piece:o,kind:i,mode:d,modeFrom:r,state:p,holders:t.filter(l=>covers(l,o)).map(l=>({...l.holder,since:l.since,until:l.until,...l.why?{why:l.why}:{}})),...notLive(p)&&n?.collected?{collected:n.collected}:{},...n?.lastUpdate?{lastUpdate:n.lastUpdate}:{}}})}},"status"),S=c((e,s,t)=>{const o=O(e);return t.filter(i=>covers(s,i)&&!o.some(d=>covers(d,i)))},"uncovered");return{status:M,stateOf:c((e,s)=>f(e,m(e),s),"stateOf"),startsHeld(e,s){const t=m(e),o=f(e,t,s);return b(t,s).driven=o,notLive(o)},async setMode(e,s,t,o){const i=m(e),d=new Set(w(e)),r=s.filter(n=>d.has(n));for(const n of r)t==="hmr"&&a.declared(e,n)===void 0?delete i.modes[n]:i.modes[n]=t;return a.save(e,{...i.modes}),a.publish?.(e,"updates-mode",{pieces:r,mode:t,...o?{by:o}:{}}),await y(e,r,{by:o}),M(e)},async hold(e,s,t={}){const o=m(e),i=a.now(),d=Math.min(Math.max(1,t.ttlSec??exports.DEFAULT_HOLD_SEC),exports.MAX_HOLD_SEC),r=holderKey(s),n=o.holds.get(r),p=t.pieces?.length?[...t.pieces]:"*",l=!n||n.until<=i?p:n.pieces==="*"||p==="*"?"*":[...new Set([...n.pieces,...p])],h={holder:{...s},pieces:l,since:n&&n.until>i?n.since:i,until:i+d*1e3,...t.why??n?.why?{why:t.why??n?.why}:{}};return o.holds.set(r,h),await y(e,w(e).filter(g=>covers(h,g))),h},async release(e,s,t){const o=m(e),i=holderKey(s),d=o.holds.get(i);return d?(o.holds.delete(i),y(e,S(o,d,w(e)),{lastRelease:!0,by:t??d.holder.name??d.holder.client})):[]},async apply(e,s,t){const o=m(e),i=w(e),d=s?.length?s.filter(r=>i.includes(r)):i;return await Promise.all(d.map(async r=>{const n=b(o,r),p=f(e,o,r);if(p==="parked")return{piece:r,outcome:"skipped",ms:0,why:"parked \u2014 set its mode to hmr or manual to start it"};if(p==="live")return{piece:r,outcome:"skipped",ms:0,why:"live \u2014 every save is already built"};const l=E(e,r);if(!l)return{piece:r,outcome:"skipped",ms:0,why:"not running in this workspace"};const h=c(async()=>v(e,n,await a.gates.update(l),t),"run"),g=n.chain.then(h,h);return n.chain=g.catch(()=>{}),g}))},collected(e,s,t){const o=u.get(e),i=o?.pieces.get(s);!o||!i||!notLive(i.driven)||(i.collected={files:t.files.slice(-MAX_FILES),...t.count!==void 0?{count:t.count}:{},skipped:t.skipped,since:i.collected?.since??a.now()})},async sweep(){const e=a.now();for(const[s,t]of u){const o=[...t.holds.entries()].filter(([,i])=>i.until<=e);for(const[i,d]of o)t.holds.delete(i),a.log?.(`[updates] ${s}: ${d.holder.name??holderKey(d.holder)}'s hold lapsed \u2014 not renewed before its lease ended (held since ${new Date(d.since).toISOString().slice(11,19)} UTC)`),await y(s,S(t,d,w(s)),{lastRelease:!0,by:"lapsed hold"})}},forget(e){u.delete(e)}}}k(createUpdates,"createUpdates"),c(createUpdates,"createUpdates");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var K=Object.defineProperty;var m=(c,s)=>K(c,"name",{value:s,configurable:!0});var E=Object.defineProperty,u=m((c,s)=>E(c,"name",{value:s,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_HMR_REFUSAL_REPORT_MS=void 0,exports.createUpgrade=createUpgrade;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),manifest_1=require("ringwall/manifest"),chooser_1=require("./chooser"),discovery_1=require("./discovery"),edge_1=require("./edge"),hmr_reload_1=require("./hmr-reload"),on_demand_1=require("./on-demand"),remote_instances_1=require("./remote-instances"),run_routes_1=require("./run-routes"),service_keys_1=require("./service-keys");exports.LENS_HMR_REFUSAL_REPORT_MS=1e4;function accountUpgrade(c,s){const l=c.svc;if(!l||s.destroyed)return;l.inflight+=1,l.lastUsed=Date.now();let i=!1;s.once("close",()=>{i||(i=!0,l.inflight-=1,l.lastUsed=Date.now())})}m(accountUpgrade,"accountUpgrade"),u(accountUpgrade,"accountUpgrade");function createUpgrade(c){const{rt:s,auth:l,proxy:i,hooks:p,obs:q,middleware:g}=c;let S=c.parkedHosts;const U=u(()=>S??=(0,on_demand_1.createParkedHostLookup)({registry:u(()=>s.registry,"registry")}),"parkedHosts"),h=new Set,k=u(e=>{e.destroyed||(h.add(e),e.once("close",()=>h.delete(e)))},"track");i.proxy.on?.("open",k);const _=new WeakMap,v=new Map,R=u((e,t)=>{const n=Date.now();n-(v.get(e.frontendKey)??0)<exports.LENS_HMR_REFUSAL_REPORT_MS||(v.set(e.frontendKey,n),console.warn(`[gateway] lens HMR socket refused: ${e.frontendKey} at ${e.target} answered ${t} for a tab on ${e.host} \u2014 that tab loads but gets no hot updates; the lens runtime reloads it once if it had a socket before.`),q?.emit("warning",`lens HMR socket refused: ${e.frontendKey} (${t})`,`cluster-lens-hmr-refused:${e.frontendKey}`,{kind:"lens-hmr-refused",frontendKey:e.frontendKey,host:e.host,target:e.target,answer:t},void 0,e.busFile))},"reportRefusal");i.proxy.on?.("proxyReqWs",(e,t)=>{const n=_.get(t);if(!n)return;const d=e;d.once("upgrade",()=>{n.answered=!0}),d.once("response",y=>{n.answered=!0,R(n,`HTTP ${y.statusCode??"?"}`)})});const H=u(async(e,t,n)=>{(0,edge_1.stripOwnedHeaders)(e);const d=(0,edge_1.canonicalize)(e.url??"/");if(d===void 0){t.destroy();return}e.url=d.path+d.query;const y=(e.headers.host||"").split(":")[0],r=(0,manifest_1.matchRoute)(s.routes,y,d.policy+d.query);if((!r||!r.host||r.host.startsWith("*."))&&U().match(y)){t.destroy();return}if(!r){t.destroy();return}if(r.run&&!(0,chooser_1.isLoopbackRequest)(e)){t.destroy();return}if(r.remote){if(!(0,chooser_1.isLoopbackRequest)(e)){t.destroy();return}(0,edge_1.resolveClientIp)(s,e),(0,edge_1.stampForwardingHeaders)(s,e);const o=(0,remote_instances_1.remoteInstanceUpstream)(r);i.proxy.ws(e,t,n,{target:o,changeOrigin:!1,agent:i.agentForTarget(o)},()=>t.destroy());return}(0,edge_1.resolveClientIp)(s,e);const a=p.upgradeContext(e,t,void 0);if(a.route=r,r.internal){const o=l.internal(e,r,void 0);if(!o.ok){t.destroy();return}a.caller=o.caller}else{if(g&&(await g.preAuth(a),a.responded()))return;const o=l.public(e,r,void 0,d.policy);if(!o.ok){t.destroy();return}if(a.claims=o.claims,p.has("afterAuth")&&(await p.run("afterAuth",a),a.responded()))return}const x=r.pool?s.serviceKeys[(0,service_keys_1.serviceKeyId)(r.svc?.wsKey,r.project)]:void 0;if(x&&(e.headers["x-internal-token"]=x),r.prependPrefix&&!e.url?.startsWith(r.prependPrefix)&&(e.url=r.prependPrefix+(e.url??"/")),(0,edge_1.stampForwardingHeaders)(s,e),g&&!r.internal&&(await g.beforeForward(a),a.responded())||p.has("onUpgrade")&&(await p.run("onUpgrade",a),a.responded()))return;const w=r.pool?(()=>{const o=(0,discovery_1.pickSock)(r.pool,s.scanTtlMs);return o?{socketPath:o}:void 0})():(0,run_routes_1.runSocketUpstream)(r)??r.target;if(!w){t.destroy();return}if(r.lens&&String(e.headers["sec-websocket-protocol"]??"").split(",").map(o=>o.trim()).includes("vite-hmr")){const o=r.lens.workspaceKey?`${r.lens.workspaceKey}:${r.lens.project}`:r.lens.project;(0,hmr_reload_1.registerHmrClient)(s,o,t);const f=!r.lens.workspaceRoot||path.resolve(r.lens.workspaceRoot)===path.resolve(s.root??"");_.set(e,{frontendKey:o,host:y,target:String(w),answered:!1,...f?{}:{busFile:path.join(r.lens.workspaceRoot,".lensmcp","events.jsonl")}})}accountUpgrade(r,t),(0,on_demand_1.touchRun)(s.registry,r,t),i.proxy.ws(e,t,n,{target:w,changeOrigin:!r.pool,agent:i.agentForTarget(w)},o=>{const f=_.get(e);f&&!f.answered&&R(f,o?.code??o?.message??"an error"),t.destroy()})},"run"),b=u(((e,t,n)=>{t.on("error",()=>t.destroy()),k(t),H(e,t,n).catch(()=>t.destroy())}),"listener");return b.closeTunnels=()=>{const e=[...h];for(const t of e)t.destroy();return h.clear(),e.length},b}m(createUpgrade,"createUpgrade"),u(createUpgrade,"createUpgrade");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var _e=Object.defineProperty;var i=(e,o)=>_e(e,"name",{value:o,configurable:!0});var ve=Object.defineProperty,s=i((e,o)=>ve(e,"name",{value:o,configurable:!0}),"s");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),fs=tslib_1.__importStar(require("node:fs")),node_child_process_1=require("node:child_process"),yaml=tslib_1.__importStar(require("js-yaml")),child_process_env_1=require("../../child-process-env"),dev_devtool_1=require("../../dev-devtool"),devserver_host_1=require("../../devserver-host"),devserver_notifier_1=require("../../devserver-notifier"),process_name_1=require("../../process-name"),worker_supervisor_1=require("../../worker-supervisor"),attach_1=require("../../shared-build/attach"),stop_on_signal_1=require("./stop-on-signal"),compile_retry_1=require("../../compile-retry"),config_files_1=require("../../config-files"),signature_1=require("../../shared-build/signature");function definedEnv(e){const o={};for(const[j,n]of Object.entries(e))typeof n=="string"&&(o[j]=n);return o}i(definedEnv,"definedEnv"),s(definedEnv,"definedEnv");const frozen=s(()=>process.env.LENSMCP_FREEZE==="1","frozen");async function*serveExecutor(e,o){process.env.NODE_ENV="development";const j=o.projectsConfigurations.projects[o.projectName],n=o.root,S=path.join(n,j.root),Q=e.outputPath?path.join(n,e.outputPath):path.join(n,"dist",j.root),ee=e.configEnv||"development",A=path.join(n,"config",`config.${ee}.yaml`),q=3050;let u=q,a=o.projectName,O={};fs.existsSync(A)?(O=yaml.load(fs.readFileSync(A,"utf8")),u=Number(O.port)||u,a=O.serviceName||a):e.port||console.warn(`[serve] ${o.projectName}: no config file at ${A} \u2014 public devserver port defaults to ${q}. If another service also lacks its config, both bind ${q} \u2192 EADDRINUSE. Add config/config.${ee}.yaml with a distinct \`port:\` (matching this project's cluster.port).`),e.serviceName&&(a=e.serviceName),e.port&&(u=e.port);const I=e.servePrefix??"",y=e.debugPort??(Number(process.env.LENSMCP_DEBUG_PORT)||void 0),ce=/^(1|true|yes|on)$/i.test((process.env.LENSMCP_DEBUG_FIXED_PORTS??"").trim()),g=e.logFile?path.resolve(n,e.logFile):process.env.LENSMCP_LOG_FILE||void 0;if(g){fs.mkdirSync(path.dirname(g),{recursive:!0}),fs.writeFileSync(g,"",{mode:384});try{fs.chmodSync(g,384)}catch{}}let M,F;e.gateway?.middleware&&(M=path.resolve(S,e.gateway.middleware),F=JSON.stringify(O));const ae=e.entryFile||"./src/deployments/service/main.ts",le=e.tsConfigFile||"./tsconfig.app.json",ue=path.resolve(S,ae),oe=path.resolve(S,le),pe=(e.workers||[]).map(r=>({entryName:r.name,entryPath:path.resolve(S,r.entryPath)})),m={appName:o.projectName,appRoot:S,outputDir:Q,main:ue,tsConfig:oe,assets:e.assets||[],additionalEntryPoints:pe,port:u,serviceName:a,memoryLimit:e.memoryLimit||8192,buildLibsFromSource:e.buildLibsFromSource!==!1,workspaceRoot:n,orgScopes:e.orgScopes||[],bundlePackages:e.bundlePackages||[],nodeExternalsConfig:e.nodeExternalsConfig,webpackConfigPath:e.webpackConfigPath,httpsReload:e.gateway?.https===!0,...e.devtool!==void 0&&{devtool:e.devtool}};let l=null,U=!1,G=!1,B=!1,h=!1;const re=path.join(__dirname,"../../main.devserver.js"),te=path.join(__dirname,"../../main.devserver.ts"),W=!fs.existsSync(re)&&fs.existsSync(te),L=W?te:re,de=path.join(Q,"main.js");function H(){l&&!l.killed&&(l.kill("SIGTERM"),l=null)}i(H,"Q"),s(H,"cleanup");function R(){h=!0,H()}i(R,"W"),s(R,"stop");const he=(0,stop_on_signal_1.stopOnSignal)({stop:R,close:s(()=>b(),"close")});process.on("exit",R);function P(){if(h||U)return;if(!fs.existsSync(L)){console.error(`[serve] devserver script not found at ${L}`);return}const r=(0,child_process_env_1.childProcessEnv)({...process.env,PORT:String(u),SERVICE_NAME:a,SERVE_PREFIX:I,LENSMCP_PROJECT:process.env.LENSMCP_PROJECT||o.projectName||a,LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE||path.join(n,".lensmcp","events.jsonl"),CHILD_COUNT:String(e.childCount||process.env.CHILD_COUNT||1),BUNDLE_PATH:de,...M&&{GATEWAY_MIDDLEWARE:M},...F&&{GATEWAY_CONFIG:F},...e.gateway?.routes?.length&&{GATEWAY_ROUTES:JSON.stringify(e.gateway.routes)},...e.gateway?.https&&{GATEWAY_HTTPS:"1"},...e.gateway?.extraPorts?.length&&{GATEWAY_EXTRA_PORTS:JSON.stringify(e.gateway.extraPorts)},...e.internalPort&&{INTERNAL_PORT:String(e.internalPort)},...y&&{LENSMCP_DEBUG_PORT:String(y)},...g&&{LENSMCP_LOG_FILE:g},...e.workers?.length&&{WORKERS:(0,worker_supervisor_1.serializeWorkerSpecs)(e.workers)},[dev_devtool_1.DEV_SOURCE_MAPS_ENV]:B?"1":"0"});if((0,devserver_host_1.devserverInProcessOffered)()&&(!W||require.extensions[".ts"])){U=!0;for(const[p,f]of Object.entries(r))f!==void 0&&(process.env[p]=f);(0,devserver_host_1.markDevserverInProcess)(),require(L),J("in this process");return}const v=["--enable-source-maps"];W&&v.unshift("--require","@swc-node/register");const c=(0,node_child_process_1.fork)(L,{cwd:n,env:r,stdio:["inherit","inherit","inherit","ipc"],execArgv:v,execPath:(0,process_name_1.namedExecPath)((0,process_name_1.processName)(process.env.LENSMCP_WS_KEY||path.basename(n),a,"dev"))});l=c,c.on("exit",(p,f)=>{l===c&&(l=null),!(f||p===0||h)&&(console.error(`[serve] devserver exited unexpectedly (code=${p}, signal=${f}) \u2014 respawning in 1.5s`),setTimeout(()=>{!h&&!l&&G&&P()},1500).unref?.())}),J()}i(P,"j"),s(P,"startDevServer");function J(r){console.log(`[serve] Devserver started on port ${u} (service: ${a}${I?`, prefix: /${I}`:""}${r?`, ${r}`:""})`),y?(console.warn(`[serve] DEBUGGER ENABLED for ${a}. Node's inspector has NO authentication \u2014 the ws:// UUID is the whole credential, and any account on this host that obtains it runs code as you. Do not enable this on a shared machine.`),ce?console.warn(`[serve] LENSMCP_DEBUG_FIXED_PORTS=1 \u2014 pod inspectors bind PREDICTABLE ports 127.0.0.1:${y}+slot (workers ${y}+20+i), reachable by any account on this host. Attach WebStorm (Attach to Node.js/Chrome) to ${y}. Unset it to bind ephemeral ports instead.`):console.log(`[serve] Debug: pod inspectors bind an EPHEMERAL 127.0.0.1 port. Get the ws:// URLs with \`lensmcp debug ${a}\` (the owner-only control socket); a devserver run in your own terminal also prints them there. Set LENSMCP_DEBUG_FIXED_PORTS=1 if your IDE needs a fixed attach port.`)):console.log(`[serve] Debug on demand: \`lensmcp debug ${a}\` opens pod inspectors without a restart`),g&&console.log(`[serve] Logs teed to ${g} \u2014 tail it in WebStorm via Run/Debug configuration \u2192 Logs tab`)}i(J,"ee"),s(J,"announceDevServer");function fe(){if(!l||l.killed){console.log("[serve] Devserver not running, restarting..."),P();return}fetch(`http://localhost:${u}/webpack/reload`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(()=>console.log("[serve] Notified devserver to reload")).catch(r=>{console.warn("[serve] Failed to notify devserver, restarting...",r.message),H(),P()})}i(fe,"me"),s(fe,"_notifyDevServerReload");let D=null;const V=[];function _(r){if(D){const v=D;D=null,v(r)}else V.push(r)}i(_,"w"),s(_,"pushResult");function se(){return V.length>0?Promise.resolve(V.shift()):new Promise(r=>{D=r})}i(se,"de"),s(se,"waitForNext");let b=s(()=>{},"closeBuild");function Y(){return!G||!l&&!U?(G=!0,P(),!0):!1}i(Y,"re"),s(Y,"builtOk");function X(){try{return JSON.stringify((0,signature_1.transpileCompilerOptions)(m.tsConfig,n))}catch{return}}i(X,"te"),s(X,"compileShape");function C(){if(h)return;const{createDevWebpackConfig:r}=require("../../create-webpack-dev"),v=require("webpack"),c=m.webpackConfigPath?path.resolve(m.appRoot,m.webpackConfigPath):void 0;if(c)try{delete require.cache[require.resolve(c)]}catch{}const p=r(m),{watch:f,...t}=p,z=(0,config_files_1.configFilesOf)(m),K=X(),{TsgoCheckPlugin:ge}=require("../../tsgo-check-plugin"),me=process.env.LENSMCP_TYPECHECK!=="off"&&!(t.plugins??[]).some(d=>d instanceof ge);let $,Z=!1;t.plugins=[...t.plugins??[],new config_files_1.ConfigFilesPlugin({files:s(()=>z,"files"),changed:s(d=>{let w=!1;if(!c||!d.includes(c)){const N=X();if(N===void 0)return;if(N===K){if(!me||d.every(k=>k===m.tsConfig))return;w=!0}}Z=($===void 0||Z)&&w,$=d.map(N=>path.relative(n,N)).sort().join(", ")},"changed")})];const T=v(t);B=(0,dev_devtool_1.bundleCarriesSourceMaps)(T.options.devtool);let E;const x=(0,compile_retry_1.createFailureRetry)(()=>{h||!E||(console.log(`[serve] ${o.projectName}: compiling again after the failure`),E.invalidate())}),ie=s((d,w)=>{if($!==void 0&&E&&!h){console.log(Z?`[serve] ${o.projectName}: ${$} changed what it type-checks with \u2014 fork-ts-checker reads that only when it starts, so a new compiler checks it`:`[serve] ${o.projectName}: ${$} changed what it compiles with \u2014 compiling again with a new compiler`),x.dispose();const k=E;E=void 0,setImmediate(()=>k.close(()=>C()));return}if(d){if(console.error("[serve] Webpack error:",d),E&&!h){const{delayMs:k,retry:Ee}=x.failed();console.log(`[serve] ${o.projectName}: compiling again in ${Math.round(k/1e3)} s (retry ${Ee}) \u2014 webpack does not after a failure like this`)}_({success:!1});return}x.succeeded();const N=w.hasErrors();if(console.info(w.toString({colors:!0,chunks:!1,assets:!0})),N){_({success:!1});return}Y(),_({success:!0,baseUrl:`http://localhost:${u}`})},"onBuild");if(frozen()){console.log(`[serve] ${o.projectName}: frozen \u2014 compiling once, no file watcher`),T.run((d,w)=>{ie(d,w),T.close(()=>{})});return}E=T.watch(p.watchOptions||{},ie),b=s(()=>{x.dispose(),E?.close(()=>{})},"closeBuild")}i(C,"L"),s(C,"compileOnItsOwn");function ne(r){const v=r.accepted.projects.filter(t=>t!==o.projectName);console.log(`[serve] ${o.projectName}: compiled by the workspace's shared compilation ${r.accepted.group.slice(0,8)}${v.length?` with ${v.join(", ")}`:""} \u2014 no webpack in this process`);const c=new devserver_notifier_1.DevserverNotifier(u,e.gateway?.https===!0,(0,devserver_notifier_1.devserverControlSock)(a)),p=(0,attach_1.createAttachedTypecheck)({appName:o.projectName,tsConfig:oe,workspaceRoot:n,memoryLimit:e.memoryLimit||8192});let f;b=s(()=>{r.close(),p.dispose()},"closeBuild"),r.listen(t=>{if(!h)switch(t.type){case"watch-run":c.watchRun(t.paths);return;case"watch-closed":c.degrade("watch closed");return;case"failed":console.error(`[serve] the shared compiler failed: ${t.message}`),c.failed(`the shared compiler failed: ${t.message}`),_({success:!1});return;case"refused":console.log(`[serve] ${o.projectName}: compiling on its own from now on \u2014 ${t.reason}`),b(),C();return;case"built":{if(console.info(t.text),B=t.sourceMaps,p.built(t),!t.ok){c.failed(),_({success:!1});return}const z=t.hash!==f;f=t.hash;const K=Y();c.built(z&&!K),_({success:!0,baseUrl:`http://localhost:${u}`});return}default:return}})}if(i(ne,"fe"),s(ne,"attachToSharedBuild"),(0,attach_1.sharedBuildOffered)()&&!frozen()){const r=await(0,attach_1.joinSharedBuild)({project:o.projectName,target:o.targetName??"serve-hmr",...o.configurationName?{configuration:o.configurationName}:{},options:m,targetOptions:{...e},env:definedEnv(process.env)});r.kind==="attached"?ne(r.session):(console.log(`[serve] ${o.projectName}: compiling on its own \u2014 ${r.reason}`),C())}else C();try{for(;;)yield await se()}finally{R(),b(),he()}}i(serveExecutor,"serveExecutor"),s(serveExecutor,"serveExecutor"),exports.default=serveExecutor,module.exports=serveExecutor,module.exports.default=serveExecutor;
|
|
1
|
+
"use strict";var Se=Object.defineProperty;var i=(e,r)=>Se(e,"name",{value:r,configurable:!0});var Ee=Object.defineProperty,t=i((e,r)=>Ee(e,"name",{value:r,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0});const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),fs=tslib_1.__importStar(require("node:fs")),node_child_process_1=require("node:child_process"),yaml=tslib_1.__importStar(require("js-yaml")),child_process_env_1=require("../../child-process-env"),dev_devtool_1=require("../../dev-devtool"),devserver_host_1=require("../../devserver-host"),devserver_notifier_1=require("../../devserver-notifier"),process_name_1=require("../../process-name"),worker_supervisor_1=require("../../worker-supervisor"),attach_1=require("../../shared-build/attach"),stop_on_signal_1=require("./stop-on-signal"),compile_retry_1=require("../../compile-retry"),config_files_1=require("../../config-files"),signature_1=require("../../shared-build/signature"),updates_gate_1=require("./updates-gate");function definedEnv(e){const r={};for(const[O,c]of Object.entries(e))typeof c=="string"&&(r[O]=c);return r}i(definedEnv,"definedEnv"),t(definedEnv,"definedEnv");const frozen=t(()=>process.env.LENSMCP_FREEZE==="1","frozen");async function*serveExecutor(e,r){process.env.NODE_ENV="development";const O=r.projectsConfigurations.projects[r.projectName],c=r.root,N=path.join(c,O.root),oe=e.outputPath?path.join(c,e.outputPath):path.join(c,"dist",O.root),te=e.configEnv||"development",q=path.join(c,"config",`config.${te}.yaml`),M=3050;let p=M,a=r.projectName,L={};fs.existsSync(q)?(L=yaml.load(fs.readFileSync(q,"utf8")),p=Number(L.port)||p,a=L.serviceName||a):e.port||console.warn(`[serve] ${r.projectName}: no config file at ${q} \u2014 public devserver port defaults to ${M}. If another service also lacks its config, both bind ${M} \u2192 EADDRINUSE. Add config/config.${te}.yaml with a distinct \`port:\` (matching this project's cluster.port).`),e.serviceName&&(a=e.serviceName),e.port&&(p=e.port);const I=e.servePrefix??"",y=e.debugPort??(Number(process.env.LENSMCP_DEBUG_PORT)||void 0),ue=/^(1|true|yes|on)$/i.test((process.env.LENSMCP_DEBUG_FIXED_PORTS??"").trim()),m=e.logFile?path.resolve(c,e.logFile):process.env.LENSMCP_LOG_FILE||void 0;if(m){fs.mkdirSync(path.dirname(m),{recursive:!0}),fs.writeFileSync(m,"",{mode:384});try{fs.chmodSync(m,384)}catch{}}let F,U;e.gateway?.middleware&&(F=path.resolve(N,e.gateway.middleware),U=JSON.stringify(L));const pe=e.entryFile||"./src/deployments/service/main.ts",de=e.tsConfigFile||"./tsconfig.app.json",he=path.resolve(N,pe),re=path.resolve(N,de),ve=(e.workers||[]).map(o=>({entryName:o.name,entryPath:path.resolve(N,o.entryPath)})),E={appName:r.projectName,appRoot:N,outputDir:oe,main:he,tsConfig:re,assets:e.assets||[],additionalEntryPoints:ve,port:p,serviceName:a,memoryLimit:e.memoryLimit||8192,buildLibsFromSource:e.buildLibsFromSource!==!1,workspaceRoot:c,orgScopes:e.orgScopes||[],bundlePackages:e.bundlePackages||[],nodeExternalsConfig:e.nodeExternalsConfig,webpackConfigPath:e.webpackConfigPath,httpsReload:e.gateway?.https===!0,...e.devtool!==void 0&&{devtool:e.devtool}};let u=null,G=!1,B=!1,W=!1,v=!1;const se=path.join(__dirname,"../../main.devserver.js"),ne=path.join(__dirname,"../../main.devserver.ts"),V=!fs.existsSync(se)&&fs.existsSync(ne),R=V?ne:se,fe=path.join(oe,"main.js");function Y(){u&&!u.killed&&(u.kill("SIGTERM"),u=null)}i(Y,"re"),t(Y,"cleanup");function D(){v=!0,Y()}i(D,"H"),t(D,"stop");const ge=(0,stop_on_signal_1.stopOnSignal)({stop:D,close:t(()=>{b(),X()},"close")});process.on("exit",D);function P(){if(v||G)return;if(!fs.existsSync(R)){console.error(`[serve] devserver script not found at ${R}`);return}const o=(0,child_process_env_1.childProcessEnv)({...process.env,PORT:String(p),SERVICE_NAME:a,SERVE_PREFIX:I,LENSMCP_PROJECT:process.env.LENSMCP_PROJECT||r.projectName||a,LENSMCP_EVENT_FILE:process.env.LENSMCP_EVENT_FILE||path.join(c,".lensmcp","events.jsonl"),CHILD_COUNT:String(e.childCount||process.env.CHILD_COUNT||1),BUNDLE_PATH:fe,...F&&{GATEWAY_MIDDLEWARE:F},...U&&{GATEWAY_CONFIG:U},...e.gateway?.routes?.length&&{GATEWAY_ROUTES:JSON.stringify(e.gateway.routes)},...e.gateway?.https&&{GATEWAY_HTTPS:"1"},...e.gateway?.extraPorts?.length&&{GATEWAY_EXTRA_PORTS:JSON.stringify(e.gateway.extraPorts)},...e.internalPort&&{INTERNAL_PORT:String(e.internalPort)},...y&&{LENSMCP_DEBUG_PORT:String(y)},...m&&{LENSMCP_LOG_FILE:m},...e.workers?.length&&{WORKERS:(0,worker_supervisor_1.serializeWorkerSpecs)(e.workers)},[dev_devtool_1.DEV_SOURCE_MAPS_ENV]:W?"1":"0"});if((0,devserver_host_1.devserverInProcessOffered)()&&(!V||require.extensions[".ts"])){G=!0;for(const[d,f]of Object.entries(o))f!==void 0&&(process.env[d]=f);(0,devserver_host_1.markDevserverInProcess)(),require(R),H("in this process");return}const l=["--enable-source-maps"];V&&l.unshift("--require","@swc-node/register");const s=(0,node_child_process_1.fork)(R,{cwd:c,env:o,stdio:["inherit","inherit","inherit","ipc"],execArgv:l,execPath:(0,process_name_1.namedExecPath)((0,process_name_1.processName)(process.env.LENSMCP_WS_KEY||path.basename(c),a,"dev"))});u=s,s.on("exit",(d,f)=>{u===s&&(u=null),!(f||d===0||v)&&(console.error(`[serve] devserver exited unexpectedly (code=${d}, signal=${f}) \u2014 respawning in 1.5s`),setTimeout(()=>{!v&&!u&&B&&P()},1500).unref?.())}),H()}i(P,"O"),t(P,"startDevServer");function H(o){console.log(`[serve] Devserver started on port ${p} (service: ${a}${I?`, prefix: /${I}`:""}${o?`, ${o}`:""})`),y?(console.warn(`[serve] DEBUGGER ENABLED for ${a}. Node's inspector has NO authentication \u2014 the ws:// UUID is the whole credential, and any account on this host that obtains it runs code as you. Do not enable this on a shared machine.`),ue?console.warn(`[serve] LENSMCP_DEBUG_FIXED_PORTS=1 \u2014 pod inspectors bind PREDICTABLE ports 127.0.0.1:${y}+slot (workers ${y}+20+i), reachable by any account on this host. Attach WebStorm (Attach to Node.js/Chrome) to ${y}. Unset it to bind ephemeral ports instead.`):console.log(`[serve] Debug: pod inspectors bind an EPHEMERAL 127.0.0.1 port. Get the ws:// URLs with \`lensmcp debug ${a}\` (the owner-only control socket); a devserver run in your own terminal also prints them there. Set LENSMCP_DEBUG_FIXED_PORTS=1 if your IDE needs a fixed attach port.`)):console.log(`[serve] Debug on demand: \`lensmcp debug ${a}\` opens pod inspectors without a restart`),m&&console.log(`[serve] Logs teed to ${m} \u2014 tail it in WebStorm via Run/Debug configuration \u2192 Logs tab`)}i(H,"se"),t(H,"announceDevServer");function me(){if(!u||u.killed){console.log("[serve] Devserver not running, restarting..."),P();return}fetch(`http://localhost:${p}/webpack/reload`,{method:"POST",headers:{"content-type":"application/json"},body:"{}"}).then(()=>console.log("[serve] Notified devserver to reload")).catch(o=>{console.warn("[serve] Failed to notify devserver, restarting...",o.message),Y(),P()})}i(me,"we"),t(me,"_notifyDevServerReload");let T=null;const J=[];function _(o){if(T){const l=T;T=null,l(o)}else J.push(o)}i(_,"w"),t(_,"pushResult");function ie(){return J.length>0?Promise.resolve(J.shift()):new Promise(o=>{T=o})}i(ie,"pe"),t(ie,"waitForNext");let b=t(()=>{},"closeBuild"),x,X=t(()=>{},"closeUpdates");function ce(){if(x||typeof process.send!="function"||!(0,devserver_host_1.inServeRunner)())return x;const o=(0,updates_gate_1.createUpdatesGate)({label:r.projectName,heldAtStart:(0,updates_gate_1.updatesHeldAtSpawn)(),send:t(s=>{process.connected&&process.send?.(s,void 0,void 0,()=>{})},"send")}),l=t(s=>{o.handle(s)},"onMessage");return process.on("message",l),x=o,X=t(()=>{process.removeListener("message",l),o.dispose()},"closeUpdates"),o}i(ce,"he"),t(ce,"updatesGate");function z(){return!B||!u&&!G?(B=!0,P(),!0):!1}i(z,"te"),t(z,"builtOk");function K(){try{return JSON.stringify((0,signature_1.transpileCompilerOptions)(E.tsConfig,c))}catch{return}}i(K,"oe"),t(K,"compileShape");function C(){if(v)return;const{createDevWebpackConfig:o}=require("../../create-webpack-dev"),l=require("webpack"),s=E.webpackConfigPath?path.resolve(E.appRoot,E.webpackConfigPath):void 0;if(s)try{delete require.cache[require.resolve(s)]}catch{}const d=o(E),{watch:f,...n}=d,Z=(0,config_files_1.configFilesOf)(E),Q=K(),{TsgoCheckPlugin:_e}=require("../../tsgo-check-plugin"),we=process.env.LENSMCP_TYPECHECK!=="off"&&!(n.plugins??[]).some(h=>h instanceof _e);let k,ee=!1;n.plugins=[...n.plugins??[],new config_files_1.ConfigFilesPlugin({files:t(()=>Z,"files"),changed:t(h=>{let w=!1;if(!s||!h.includes(s)){const S=K();if(S===void 0)return;if(S===Q){if(!we||h.every(j=>j===E.tsConfig))return;w=!0}}ee=(k===void 0||ee)&&w,k=h.map(S=>path.relative(c,S)).sort().join(", ")},"changed")})];const $=l(n);W=(0,dev_devtool_1.bundleCarriesSourceMaps)($.options.devtool);let g;const A=(0,compile_retry_1.createFailureRetry)(()=>{v||!g||(console.log(`[serve] ${r.projectName}: compiling again after the failure`),g.invalidate())}),le=t((h,w)=>{if(k!==void 0&&g&&!v){console.log(ee?`[serve] ${r.projectName}: ${k} changed what it type-checks with \u2014 fork-ts-checker reads that only when it starts, so a new compiler checks it`:`[serve] ${r.projectName}: ${k} changed what it compiles with \u2014 compiling again with a new compiler`),A.dispose(),x?.superseded();const j=g;g=void 0,setImmediate(()=>j.close(()=>C()));return}if(h){if(console.error("[serve] Webpack error:",h),g&&!v){const{delayMs:j,retry:ye}=A.failed();console.log(`[serve] ${r.projectName}: compiling again in ${Math.round(j/1e3)} s (retry ${ye}) \u2014 webpack does not after a failure like this`)}_({success:!1});return}A.succeeded();const S=w.hasErrors();if(console.info(w.toString({colors:!0,chunks:!1,assets:!0})),S){_({success:!1});return}z(),_({success:!0,baseUrl:`http://localhost:${p}`})},"onBuild");if(frozen()){console.log(`[serve] ${r.projectName}: frozen \u2014 compiling once, no file watcher`),$.run((h,w)=>{le(h,w),$.close(()=>{})});return}g=$.watch(d.watchOptions||{},le),ce()?.attach($,g),b=t(()=>{A.dispose(),g?.close(()=>{})},"closeBuild")}i(C,"T"),t(C,"compileOnItsOwn");function ae(o){const l=o.accepted.projects.filter(n=>n!==r.projectName);console.log(`[serve] ${r.projectName}: compiled by the workspace's shared compilation ${o.accepted.group.slice(0,8)}${l.length?` with ${l.join(", ")}`:""} \u2014 no webpack in this process`);const s=new devserver_notifier_1.DevserverNotifier(p,e.gateway?.https===!0,(0,devserver_notifier_1.devserverControlSock)(a)),d=(0,attach_1.createAttachedTypecheck)({appName:r.projectName,tsConfig:re,workspaceRoot:c,memoryLimit:e.memoryLimit||8192});let f;b=t(()=>{o.close(),d.dispose()},"closeBuild"),o.listen(n=>{if(!v)switch(n.type){case"watch-run":s.watchRun(n.paths);return;case"watch-closed":s.degrade("watch closed");return;case"failed":console.error(`[serve] the shared compiler failed: ${n.message}`),s.failed(`the shared compiler failed: ${n.message}`),_({success:!1});return;case"refused":console.log(`[serve] ${r.projectName}: compiling on its own from now on \u2014 ${n.reason}`),b(),C();return;case"built":{if(console.info(n.text),W=n.sourceMaps,d.built(n),!n.ok){s.failed(),_({success:!1});return}const Z=n.hash!==f;f=n.hash;const Q=z();s.built(Z&&!Q),_({success:!0,baseUrl:`http://localhost:${p}`});return}default:return}})}if(i(ae,"ge"),t(ae,"attachToSharedBuild"),(0,attach_1.sharedBuildOffered)()&&!frozen()){const o=await(0,attach_1.joinSharedBuild)({project:r.projectName,target:r.targetName??"serve-hmr",...r.configurationName?{configuration:r.configurationName}:{},options:E,targetOptions:{...e},env:definedEnv(process.env)});o.kind==="attached"?ae(o.session):(console.log(`[serve] ${r.projectName}: compiling on its own \u2014 ${o.reason}`),C())}else C();try{for(;;)yield await ie()}finally{D(),b(),X(),ge()}}i(serveExecutor,"serveExecutor"),t(serveExecutor,"serveExecutor"),exports.default=serveExecutor,module.exports=serveExecutor,module.exports.default=serveExecutor;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
export declare const UPDATES_CHANNEL = "lensmcp-updates";
|
|
2
|
+
/** Set by the gateway at spawn: the runner holds after its first build (a rolled generation starts held). */
|
|
3
|
+
export declare const UPDATES_HELD_ENV = "LENSMCP_UPDATES_HELD";
|
|
4
|
+
export type UpdatesRequest = 'hold' | 'release' | 'update';
|
|
5
|
+
/** gateway → runner. */
|
|
6
|
+
export interface UpdatesRunnerInbound {
|
|
7
|
+
channel: typeof UPDATES_CHANNEL;
|
|
8
|
+
type: UpdatesRequest;
|
|
9
|
+
}
|
|
10
|
+
/** runner → gateway, while held: what the hold collected since the last compile took the collection. */
|
|
11
|
+
export interface UpdatesHeldMessage {
|
|
12
|
+
channel: typeof UPDATES_CHANNEL;
|
|
13
|
+
type: 'held';
|
|
14
|
+
/** The files saved (or removed), absolute, the most recently saved last — at most {@link HELD_REPORT_FILES}. */
|
|
15
|
+
files: string[];
|
|
16
|
+
/** How many files that is, all of them. */
|
|
17
|
+
count: number;
|
|
18
|
+
/** Change batches heard while held: each one a compile the hold avoided. */
|
|
19
|
+
skipped: number;
|
|
20
|
+
}
|
|
21
|
+
/** runner → gateway: the end of what an `update` or a `release` asked for. */
|
|
22
|
+
export interface UpdatesBuiltMessage {
|
|
23
|
+
channel: typeof UPDATES_CHANNEL;
|
|
24
|
+
type: 'built';
|
|
25
|
+
/** The build has no errors (a request with nothing to compile: `true`). */
|
|
26
|
+
ok: boolean;
|
|
27
|
+
/** The bundle differs from the last good build's — what serves after it is new. */
|
|
28
|
+
changed: boolean;
|
|
29
|
+
/** The build's errors, as webpack prints them — at most {@link MAX_ERRORS}, each at most {@link MAX_ERROR_CHARS}. */
|
|
30
|
+
errors?: string[];
|
|
31
|
+
ms: number;
|
|
32
|
+
}
|
|
33
|
+
export type UpdatesRunnerOutbound = UpdatesHeldMessage | UpdatesBuiltMessage;
|
|
34
|
+
export declare const HELD_REPORT_FILES = 50;
|
|
35
|
+
export declare const HELD_REPORT_EVERY_MS = 1000;
|
|
36
|
+
export declare const MAX_ERRORS = 30;
|
|
37
|
+
export declare const MAX_ERROR_CHARS = 4000;
|
|
38
|
+
/** Strictly this channel's: the runner's IPC also carries the gateway's task and the shared-build relay. */
|
|
39
|
+
export declare function isUpdatesRunnerInbound(m: unknown): m is UpdatesRunnerInbound;
|
|
40
|
+
/** Did the gateway start this runner held? */
|
|
41
|
+
export declare function updatesHeldAtSpawn(env?: NodeJS.ProcessEnv): boolean;
|
|
42
|
+
/** The parts of webpack's `Watching` the gate drives and reads (webpack 5 lib/Watching.js). */
|
|
43
|
+
export interface GateWatching {
|
|
44
|
+
suspended: boolean;
|
|
45
|
+
running: boolean;
|
|
46
|
+
invalid?: boolean;
|
|
47
|
+
/** The armed watcher: `null` from a compile's start until `_done` watches again — and for good after a compile that
|
|
48
|
+
* failed outright, which never watches again. */
|
|
49
|
+
watcher?: unknown;
|
|
50
|
+
watchOptions?: object;
|
|
51
|
+
/** Read only: set by every batch merged since the last compile took the collection. */
|
|
52
|
+
_collectedChangedFiles?: ReadonlySet<string>;
|
|
53
|
+
_collectedRemovedFiles?: ReadonlySet<string>;
|
|
54
|
+
suspend(): void;
|
|
55
|
+
resume(): void;
|
|
56
|
+
}
|
|
57
|
+
interface Tap<A extends unknown[]> {
|
|
58
|
+
tap(name: string, fn: (...args: A) => void): void;
|
|
59
|
+
}
|
|
60
|
+
/** The parts of a webpack `Stats` the gate reads. */
|
|
61
|
+
export interface GateStats {
|
|
62
|
+
hasErrors(): boolean;
|
|
63
|
+
compilation?: {
|
|
64
|
+
chunks?: Iterable<{
|
|
65
|
+
id?: unknown;
|
|
66
|
+
hash?: string | null;
|
|
67
|
+
}>;
|
|
68
|
+
fileDependencies?: Iterable<string>;
|
|
69
|
+
contextDependencies?: Iterable<string>;
|
|
70
|
+
missingDependencies?: Iterable<string>;
|
|
71
|
+
};
|
|
72
|
+
toJson?(options: object): {
|
|
73
|
+
errors?: Array<{
|
|
74
|
+
message?: string;
|
|
75
|
+
moduleName?: string;
|
|
76
|
+
loc?: string;
|
|
77
|
+
}>;
|
|
78
|
+
errorsCount?: number;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** The compiler hooks the gate taps. */
|
|
82
|
+
export interface GateCompiler {
|
|
83
|
+
hooks: {
|
|
84
|
+
watchRun: Tap<[unknown]>;
|
|
85
|
+
done: Tap<[GateStats]>;
|
|
86
|
+
afterDone: Tap<[unknown]>;
|
|
87
|
+
failed: Tap<[Error]>;
|
|
88
|
+
};
|
|
89
|
+
/** When the running compile began — set by `_go` before it takes the collection. */
|
|
90
|
+
fsStartTime?: number;
|
|
91
|
+
}
|
|
92
|
+
/** What a build depends on — what the listener watches. */
|
|
93
|
+
export interface GateDependencies {
|
|
94
|
+
files: Iterable<string>;
|
|
95
|
+
directories: Iterable<string>;
|
|
96
|
+
missing: Iterable<string>;
|
|
97
|
+
}
|
|
98
|
+
export interface ChangeListener {
|
|
99
|
+
close(): void;
|
|
100
|
+
}
|
|
101
|
+
/** Listen for saves while held — `undefined` when nothing can (no watchpack, or no watch options to share). */
|
|
102
|
+
export type ListenFn = (deps: GateDependencies, watchOptions: object | undefined, startTime: number | undefined, on: {
|
|
103
|
+
change(file: string): void;
|
|
104
|
+
batch(): void;
|
|
105
|
+
}) => ChangeListener | undefined;
|
|
106
|
+
interface WatchpackLike {
|
|
107
|
+
on(event: 'change' | 'remove', fn: (file: string) => void): void;
|
|
108
|
+
on(event: 'aggregated', fn: () => void): void;
|
|
109
|
+
watch(options: {
|
|
110
|
+
files: Iterable<string>;
|
|
111
|
+
directories: Iterable<string>;
|
|
112
|
+
missing: Iterable<string>;
|
|
113
|
+
startTime?: number;
|
|
114
|
+
}): void;
|
|
115
|
+
close(): void;
|
|
116
|
+
}
|
|
117
|
+
type WatchpackCtor = new (options: object) => WatchpackLike;
|
|
118
|
+
/**
|
|
119
|
+
* A second watchpack over the build's dependencies. Constructed with the Watching's own `watchOptions` OBJECT: watchpack
|
|
120
|
+
* caches its directory watchers by that object (normalizeCache, getWatcherManager), so this one rides on webpack's —
|
|
121
|
+
* one more listener per file, no second `fs.watch`. It never pauses, so it hears every save, re-saves included.
|
|
122
|
+
*/
|
|
123
|
+
export declare function watchpackListen(resolve?: () => WatchpackCtor | undefined): ListenFn;
|
|
124
|
+
export interface UpdatesGateOptions {
|
|
125
|
+
send(message: UpdatesRunnerOutbound): void;
|
|
126
|
+
/** Held from the first compile on ({@link updatesHeldAtSpawn}). */
|
|
127
|
+
heldAtStart?: boolean;
|
|
128
|
+
/** For the lines it prints. */
|
|
129
|
+
label?: string;
|
|
130
|
+
log?: (line: string) => void;
|
|
131
|
+
listen?: ListenFn;
|
|
132
|
+
now?: () => number;
|
|
133
|
+
reportEveryMs?: number;
|
|
134
|
+
}
|
|
135
|
+
export interface UpdatesGate {
|
|
136
|
+
/** A message from the gateway: `true` when it was this channel's (and is handled). */
|
|
137
|
+
handle(message: unknown): boolean;
|
|
138
|
+
/** The service's compiler and its Watching — again whenever a new compiler replaces the last. Before its first compile. */
|
|
139
|
+
attach(compiler: GateCompiler, watching: GateWatching): void;
|
|
140
|
+
/** The build that just ended is not this compiler's last word: a new one replaces it (serve.impl's reconfigure). */
|
|
141
|
+
superseded(): void;
|
|
142
|
+
/** Suspended by a hold, now. */
|
|
143
|
+
readonly held: boolean;
|
|
144
|
+
dispose(): void;
|
|
145
|
+
}
|
|
146
|
+
export declare function createUpdatesGate(opts: UpdatesGateOptions): UpdatesGate;
|
|
147
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var B=Object.defineProperty;var _=(s,t)=>B(s,"name",{value:t,configurable:!0});var J=Object.defineProperty,n=_((s,t)=>J(s,"name",{value:t,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_ERROR_CHARS=exports.MAX_ERRORS=exports.HELD_REPORT_EVERY_MS=exports.HELD_REPORT_FILES=exports.UPDATES_HELD_ENV=exports.UPDATES_CHANNEL=void 0,exports.isUpdatesRunnerInbound=isUpdatesRunnerInbound,exports.updatesHeldAtSpawn=updatesHeldAtSpawn,exports.watchpackListen=watchpackListen,exports.createUpdatesGate=createUpdatesGate;const tslib_1=require("tslib"),node_crypto_1=require("node:crypto"),path=tslib_1.__importStar(require("node:path"));exports.UPDATES_CHANNEL="lensmcp-updates",exports.UPDATES_HELD_ENV="LENSMCP_UPDATES_HELD",exports.HELD_REPORT_FILES=50,exports.HELD_REPORT_EVERY_MS=1e3,exports.MAX_ERRORS=30,exports.MAX_ERROR_CHARS=4e3;const REQUESTS=new Set(["hold","release","update"]);function isUpdatesRunnerInbound(s){const t=s;return!!t&&typeof t=="object"&&t.channel===exports.UPDATES_CHANNEL&&typeof t.type=="string"&&REQUESTS.has(t.type)}_(isUpdatesRunnerInbound,"isUpdatesRunnerInbound"),n(isUpdatesRunnerInbound,"isUpdatesRunnerInbound");function updatesHeldAtSpawn(s=process.env){return s[exports.UPDATES_HELD_ENV]?.trim()==="1"}_(updatesHeldAtSpawn,"updatesHeldAtSpawn"),n(updatesHeldAtSpawn,"updatesHeldAtSpawn");function webpacksWatchpack(){try{const s=path.dirname(require.resolve("webpack"));return require(require.resolve("watchpack",{paths:[s]}))}catch{return}}_(webpacksWatchpack,"webpacksWatchpack"),n(webpacksWatchpack,"webpacksWatchpack");function watchpackListen(s=webpacksWatchpack){return(t,l,o,u)=>{const h=l?s():void 0;if(!h||!l)return;const a=new h(l);return a.on("change",d=>u.change(d)),a.on("remove",d=>u.change(d)),a.on("aggregated",()=>u.batch()),a.watch({files:t.files,directories:t.directories,missing:t.missing,...o?{startTime:o}:{}}),{close:n(()=>a.close(),"close")}}}_(watchpackListen,"watchpackListen"),n(watchpackListen,"watchpackListen");function bundleDigest(s){const t=s.compilation?.chunks;if(!t)return;const l=[];for(const o of t)l.push(`${String(o.id)}:${o.hash??""}`);return(0,node_crypto_1.createHash)("sha256").update(l.sort().join("|")).digest("hex").slice(0,16)}_(bundleDigest,"bundleDigest"),n(bundleDigest,"bundleDigest");function errorsOf(s){let t;try{t=s.toJson?.({all:!1,errors:!0,errorsCount:!0})}catch{return["the build failed (its errors could not be read)"]}const l=t?.errors??[],o=l.slice(0,exports.MAX_ERRORS).map(h=>{const a=`${h.moduleName?`ERROR in ${h.moduleName}${h.loc?` ${h.loc}`:""}`:"ERROR"}
|
|
2
|
+
${String(h.message??"").trim()}`;return a.length>exports.MAX_ERROR_CHARS?`${a.slice(0,exports.MAX_ERROR_CHARS)}\u2026`:a}),u=Math.max(t?.errorsCount??0,l.length);return u>o.length&&o.push(`\u2026 and ${u-o.length} more`),o.length?o:["the build failed"]}_(errorsOf,"errorsOf"),n(errorsOf,"errorsOf");function createUpdatesGate(s){const t=s.now??Date.now,l=s.listen??watchpackListen(),o=s.log??(e=>console.log(e)),u=s.label?`${s.label}: `:"",h=s.reportEveryMs??exports.HELD_REPORT_EVERY_MS,a="LensmcpUpdatesGate";let d=s.heldAtStart===!0,m=!1,i,O,R=0,A=!1,v=!1,X,y,q,w,S,U=[];const T=[];let P;const f=new Map;let L=0,F=0,x;const b=n(()=>!!i&&d&&i.suspended,"isHeld"),C=n(()=>!i||!A||v||i.running,"busy"),V=n(e=>{try{s.send(e)}catch{}},"send"),j=n(()=>{if(x=void 0,!b()||m)return;F=t();const e=[...f.keys()];V({channel:exports.UPDATES_CHANNEL,type:"held",files:e.slice(-exports.HELD_REPORT_FILES),count:e.length,skipped:L})},"report"),D=n(()=>{if(!b()||x||m)return;const e=F+h-t();if(e<=0)return j();x=setTimeout(j,e),x.unref?.()},"scheduleReport"),M=n(()=>{x&&clearTimeout(x),x=void 0},"stopReporting"),k=n(()=>{P?.close(),P=void 0},"closeListener"),G=n(()=>{if(!i||!y||!b())return;const e=P?t():X,c=l(y,i.watchOptions,e,{change:n(r=>{f.delete(r),f.set(r,!0),D()},"change"),batch:n(()=>{L+=1,D()},"batch")});k(),P=c},"armListener"),N=n(()=>{k(),M(),f.clear(),L=0},"goLive"),W=n(e=>!!(f.size>0||!("_collectedChangedFiles"in e)||e._collectedChangedFiles!==void 0||e._collectedRemovedFiles!==void 0||e.invalid||!e.watcher),"somethingCollected"),$=n((e,c)=>{const r=t(),p=S&&!S.ok?S:void 0;for(const E of e){const g=c&&E.waited?c:p??{ok:!0,changed:!1};V({channel:exports.UPDATES_CHANNEL,type:"built",ok:g.ok,changed:g.changed,...g.errors?.length?{errors:g.errors}:{},ms:c&&E.waited?r-E.at:0})}},"answer"),I=n(()=>{if(m||!i||C()||T.length===0)return;const e=i,c=T.splice(0);if(!e.suspended){$(c,S);return}if(!W(e)){d||(e.suspended=!1,N(),o(`[serve] ${u}live again \u2014 nothing was held, nothing to compile`)),$(c,S),d&&D();return}const r=f.size,p=r?`${r} held change${r===1?"":"s"}`:"what was held";if(v=!0,e.resume(),d&&e.suspend(),!e.running){v=!1,d||N(),$(c,void 0);return}f.clear(),L=0,U.push(...c),d?o(`[serve] ${u}update \u2014 compiling ${p}, then holding again`):(N(),o(`[serve] ${u}live again \u2014 compiling ${p}`))},"drain"),Y=n(e=>{if(e!==R||m)return;v=!1,w&&(S=w,w=void 0);const c=U;U=[],$(c.map(r=>({...r,waited:!0})),S),b()&&(G(),D()),I()},"settle"),z=n(()=>{!i||i.suspended||(i.suspend(),o(`[serve] ${u}held \u2014 saves are collected, not compiled, until an update or a release`),G(),D())},"suspendHeld");return{get held(){return b()},handle(e){if(!isUpdatesRunnerInbound(e))return!1;if(m)return!0;switch(e.type){case"hold":return d=!0,i&&A&&(i.suspended?D():z()),!0;case"release":return d=!1,T.push({at:t(),waited:C()}),I(),!0;case"update":return T.push({at:t(),waited:C()}),I(),!0}return!0},attach(e,c){if(m)return;R+=1;const r=R;O=e,i=c,A=!1,v=!1,k(),e.hooks.watchRun.tap(a,()=>{r===R&&(X=O?.fsStartTime??t(),v=!0,A||(A=!0,f.clear(),L=0,d&&z()))}),e.hooks.done.tap(a,p=>{if(r!==R)return;const E=!p.hasErrors(),g=bundleDigest(p),Q=E&&(g===void 0||g!==q);E&&g!==void 0&&(q=g),w=E?{ok:E,changed:Q}:{ok:E,changed:!1,errors:errorsOf(p)};const H=p.compilation;H?.fileDependencies&&H.contextDependencies&&H.missingDependencies&&(y={files:H.fileDependencies,directories:H.contextDependencies,missing:H.missingDependencies})}),e.hooks.afterDone.tap(a,()=>{r===R&&setImmediate(()=>Y(r))}),e.hooks.failed.tap(a,p=>{r===R&&(w={ok:!1,changed:!1,errors:[String(p?.message??p).slice(0,exports.MAX_ERROR_CHARS)]},setImmediate(()=>Y(r)))})},superseded(){R+=1,i=void 0,O=void 0,A=!1,v=!1,w=void 0,k(),M()},dispose(){m=!0,R+=1,k(),M(),i=void 0,O=void 0}}}_(createUpdatesGate,"createUpdatesGate"),n(createUpdatesGate,"createUpdatesGate");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var y=Object.defineProperty;var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var h=(r,e)=>y(r,"name",{value:e,configurable:!0});var f=Object.defineProperty,u=h((r,e)=>f(r,"name",{value:e,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=trustExecutor,exports.missingHostLines=missingHostLines,exports.collectHosts=collectHosts;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),services_decl_1=require("../gateway/runtime/services-decl"),node_dns_1=require("node:dns"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),basic_ssl_1=require("../../basic-ssl"),checkout_cache_1=require("../../checkout-cache"),hostname_1=require("./hostname");async function trustExecutor(r,e){const t=(0,checkout_cache_1.checkoutCacheDir)(e.root,"davnx-webpack"),n=(0,basic_ssl_1.ensureCaSync)(t),i=process.env.LENSMCP_TRUST_HOSTS_ONLY==="1",s=collectHosts(r,e);if(s.length===0&&console.log("[trust] no concrete hostnames found (only wildcards?) \u2014 keychain step only."),process.platform!=="darwin"){console.log("[trust] non-macOS platform \u2014 do these manually:"),console.log(` \u2022 trust ${n} in your OS/browser store (Linux: update-ca-certificates / certutil)`);for(const c of s)console.log(` \u2022 /etc/hosts: "127.0.0.1 ${c}" and "::1 ${c}"`);return{success:!0}}const a=caSha256Fingerprint(n),o=i||a!==void 0&&(0,node_child_process_1.spawnSync)("security",["find-certificate","-a","-c","lensmcp local dev CA","-Z","/Library/Keychains/System.keychain"],{encoding:"utf8"}).stdout?.includes(a)===!0;if(i)console.log("[trust] hosts-only: a shared daemon serves TLS with its own CA \u2014 skipping the keychain step.");else if(o)console.log("[trust] CA already in the System keychain \u2014 skipping.");else{if(console.log(`[trust] adding CA to the System keychain (sudo will prompt): ${n}`),(0,node_child_process_1.spawnSync)("sudo",["security","add-trusted-cert","-d","-r","trustRoot","-k","/Library/Keychains/System.keychain",n],{stdio:"inherit"}).status!==0)return console.error("[trust] add-trusted-cert failed \u2014 rerun in a terminal so sudo can prompt."),{success:!1};console.log("[trust] CA trusted. Restart your browser once (it caches certificate verdicts).")}const d=fs.readFileSync("/etc/hosts","utf8"),l=missingHostLines(s,d,await resolveAll(s));if(l.length===0)console.log("[trust] /etc/hosts already complete (both families for every hostname, by a line or by the OS resolver).");else{if(console.log(`[trust] appending to /etc/hosts (sudo):
|
|
2
2
|
${l.join(`
|
|
3
3
|
`)}`),(0,node_child_process_1.spawnSync)("sudo",["tee","-a","/etc/hosts"],{input:l.join(`
|
|
4
4
|
`)+`
|
|
5
|
-
`,stdio:["pipe","ignore","inherit"]}).status!==0)return console.error("[trust] /etc/hosts update failed."),{success:!1};(0,node_child_process_1.spawnSync)("sudo",["dscacheutil","-flushcache"],{stdio:"inherit"}),(0,node_child_process_1.spawnSync)("sudo",["killall","-HUP","mDNSResponder"],{stdio:"inherit"})}if(!i){const c=(0,node_child_process_1.spawnSync)("security",["verify-cert","-c",n,"-p","basic"],{stdio:"ignore"});console.log(`[trust] CA trust check: ${c.status===0?"OK":"NOT TRUSTED YET (browser restart may be needed)"}`)}for(const c of s)console.log(`[trust] ${c} \u2192 https ready (hosts + cert SAN ride the gateway config)`);return{success:!0}}
|
|
6
|
-
`).some(o=>{const d=o.trim();if(d.startsWith("#"))return!1;const l=d.split(/\s+/);return l[0]===s&&l.slice(1).includes(a)}),"hasEntry"),i=[];for(const s of r)!n("127.0.0.1",s)&&!t.get(s)?.v4&&i.push(`127.0.0.1 ${s}`),!n("::1",s)&&!t.get(s)?.v6&&i.push(`::1 ${s}`);return i}
|
|
5
|
+
`,stdio:["pipe","ignore","inherit"]}).status!==0)return console.error("[trust] /etc/hosts update failed."),{success:!1};(0,node_child_process_1.spawnSync)("sudo",["dscacheutil","-flushcache"],{stdio:"inherit"}),(0,node_child_process_1.spawnSync)("sudo",["killall","-HUP","mDNSResponder"],{stdio:"inherit"})}if(!i){const c=(0,node_child_process_1.spawnSync)("security",["verify-cert","-c",n,"-p","basic"],{stdio:"ignore"});console.log(`[trust] CA trust check: ${c.status===0?"OK":"NOT TRUSTED YET (browser restart may be needed)"}`)}for(const c of s)console.log(`[trust] ${c} \u2192 https ready (hosts + cert SAN ride the gateway config)`);return{success:!0}}h(trustExecutor,"trustExecutor"),u(trustExecutor,"trustExecutor");function caSha256Fingerprint(r){const e=(0,node_child_process_1.spawnSync)("openssl",["x509","-in",r,"-noout","-fingerprint","-sha256"],{encoding:"utf8"});if(e.status!==0||!e.stdout)return;const t=e.stdout.split("=")[1]?.replaceAll(":","").trim().toUpperCase();return t&&/^[0-9A-F]{64}$/.test(t)?t:void 0}h(caSha256Fingerprint,"caSha256Fingerprint"),u(caSha256Fingerprint,"caSha256Fingerprint");function missingHostLines(r,e,t){const n=u((s,a)=>e.split(`
|
|
6
|
+
`).some(o=>{const d=o.trim();if(d.startsWith("#"))return!1;const l=d.split(/\s+/);return l[0]===s&&l.slice(1).includes(a)}),"hasEntry"),i=[];for(const s of r)!n("127.0.0.1",s)&&!t.get(s)?.v4&&i.push(`127.0.0.1 ${s}`),!n("::1",s)&&!t.get(s)?.v6&&i.push(`::1 ${s}`);return i}h(missingHostLines,"missingHostLines"),u(missingHostLines,"missingHostLines");async function resolveAll(r){const e=u(t=>new Promise(n=>{const i=setTimeout(()=>n({v4:!1,v6:!1}),2e3);(0,node_dns_1.lookup)(t,{all:!0},(s,a)=>{if(clearTimeout(i),s||!Array.isArray(a))return n({v4:!1,v6:!1});n({v4:a.some(o=>o.family===4&&o.address.startsWith("127.")),v6:a.some(o=>o.family===6&&o.address==="::1")})})}),"one");return new Map(await Promise.all(r.map(async t=>[t,await e(t)])))}h(resolveAll,"resolveAll"),u(resolveAll,"resolveAll");function collectHosts(r,e){const t=[],n=e.projectName?e.projectsConfigurations?.projects[e.projectName]:void 0,i=r.serveTarget??"serve-hmr",s=n?.targets?.[i]?.options?.gateway?.routes??[];for(const o of s)o.host&&(0,hostname_1.isValidHostname)(o.host)?t.push(o.host):o.host&&console.warn(`[trust] ignoring invalid hostname in ${i} routes: ${JSON.stringify(o.host)}`);const{services:a}=(0,services_decl_1.lensmcpServices)(e.root);for(const[o,d]of Object.entries(e.projectsConfigurations?.projects??{}))try{const l=(0,services_decl_1.readJson)(path.join(e.root,d.root,"project.json")),{decl:c}=(0,services_decl_1.declFor)(a,o,l),p=c?.host;p&&!(0,hostname_1.isValidHostname)(p)&&console.warn(`[trust] ignoring invalid hostname in ${d.root}/project.json: ${JSON.stringify(p)}`),p&&(0,hostname_1.isValidHostname)(p)&&(t.push(p),c?.service&&c.internalHost!==!1&&t.push(typeof c.internalHost=="string"?c.internalHost:`internal.${p}`))}catch{}return[...new Set([...t,"lensmcp.local",...r.hosts??[]])]}h(collectHosts,"collectHosts"),u(collectHosts,"collectHosts");
|