vite-plugin-windmill 1.683.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.mjs ADDED
@@ -0,0 +1,1044 @@
1
+ import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { ApiError, AppService, JobService, setClient } from "windmill-client";
4
+ import { createHash } from "node:crypto";
5
+ import { parse } from "yaml";
6
+ import { Readable } from "node:stream";
7
+ import { scheduler } from "node:timers/promises";
8
+ import { loadEnv } from "vite";
9
+ //#region src/project.ts
10
+ const WMILL_IMPORT_PATTERN = /^(?:\.\/|\/)?wmill(?:\.ts)?$|^(?:\.\.\/)+wmill(?:\.ts)?$/;
11
+ const RAW_APP_FOLDER_SUFFIXES = [".raw_app", "__raw_app"];
12
+ const RAW_APP_FILE_NAME = "raw_app.yaml";
13
+ const WMILL_CONFIG_FILE_NAME = "wmill.yaml";
14
+ const DEPLOY_IGNORED_FILE_NAMES = new Set([
15
+ "AGENTS.md",
16
+ "DATATABLES.md",
17
+ "package-lock.json",
18
+ "raw_app.yaml",
19
+ "wmill.d.ts"
20
+ ]);
21
+ const DEPLOY_IGNORED_DIRECTORIES = new Set([
22
+ ".claude",
23
+ "backend",
24
+ "dist",
25
+ "node_modules",
26
+ "sql_to_apply"
27
+ ]);
28
+ const LANGUAGE_BY_EXTENSION = {
29
+ "bq.sql": "bigquery",
30
+ "bun.ts": "bun",
31
+ cs: "csharp",
32
+ "deno.ts": "deno",
33
+ "duckdb.sql": "duckdb",
34
+ "frontend.js": "frontend",
35
+ go: "go",
36
+ gql: "graphql",
37
+ java: "java",
38
+ "ms.sql": "mssql",
39
+ "my.sql": "mysql",
40
+ "native.ts": "nativets",
41
+ nu: "nu",
42
+ "odb.sql": "oracledb",
43
+ "pg.sql": "postgresql",
44
+ php: "php",
45
+ "playbook.yml": "ansible",
46
+ ps1: "powershell",
47
+ py: "python3",
48
+ rb: "ruby",
49
+ rs: "rust",
50
+ "sf.sql": "snowflake",
51
+ sh: "bash",
52
+ ts: "bun"
53
+ };
54
+ const isNodeError = (value) => value instanceof Error && "code" in value;
55
+ const pathExists = async (filePath) => {
56
+ try {
57
+ await access(filePath);
58
+ return true;
59
+ } catch {
60
+ return false;
61
+ }
62
+ };
63
+ const normalizeToPosix = (value) => value.split(path.sep).join("/");
64
+ const dirnameIfPossible = (value) => {
65
+ const parent = path.dirname(value);
66
+ return parent === value ? void 0 : parent;
67
+ };
68
+ const findUp = async (startDir, fileName) => {
69
+ let currentDir = path.resolve(startDir);
70
+ while (true) {
71
+ const candidate = path.join(currentDir, fileName);
72
+ if (await pathExists(candidate)) return candidate;
73
+ const parentDir = dirnameIfPossible(currentDir);
74
+ if (!parentDir) return void 0;
75
+ currentDir = parentDir;
76
+ }
77
+ };
78
+ const parseYamlFile = async (filePath) => {
79
+ return parse(await readFile(filePath, "utf8"));
80
+ };
81
+ const resolveRoot = async (explicitRoot, dir) => {
82
+ if (explicitRoot) {
83
+ const root = path.resolve(explicitRoot);
84
+ return {
85
+ path: await pathExists(path.join(root, WMILL_CONFIG_FILE_NAME)) ? path.join(root, WMILL_CONFIG_FILE_NAME) : void 0,
86
+ root
87
+ };
88
+ }
89
+ const configPath = await findUp(dir, WMILL_CONFIG_FILE_NAME);
90
+ return {
91
+ path: configPath,
92
+ root: configPath ? path.dirname(configPath) : dir
93
+ };
94
+ };
95
+ const resolveDir = async (explicitDir) => {
96
+ const candidate = path.resolve(explicitDir ?? process.cwd());
97
+ const rawAppPath = await findUp(candidate, RAW_APP_FILE_NAME);
98
+ if (!rawAppPath) throw new Error(`Could not find ${RAW_APP_FILE_NAME} from ${candidate}`);
99
+ return path.dirname(rawAppPath);
100
+ };
101
+ const stripRawAppSuffix = (folderName) => {
102
+ for (const suffix of RAW_APP_FOLDER_SUFFIXES) if (folderName.endsWith(suffix)) return folderName.slice(0, -suffix.length);
103
+ };
104
+ const inferPath = (dir, root) => {
105
+ const segments = normalizeToPosix(path.relative(root, dir)).split("/").filter(Boolean);
106
+ if (segments.length === 0) throw new Error(`Could not infer a Windmill app path from ${dir}`);
107
+ const lastSegment = segments.at(-1);
108
+ if (!lastSegment) throw new Error(`Could not infer a Windmill app path from ${dir}`);
109
+ const strippedSegment = stripRawAppSuffix(lastSegment);
110
+ if (!strippedSegment) throw new Error(`Expected ${dir} to end in .raw_app or __raw_app so the app path can be inferred`);
111
+ return [...segments.slice(0, -1), strippedSegment].join("/");
112
+ };
113
+ const inferBase = (pathValue) => `/apps_raw/get/${pathValue}/`;
114
+ const resolveEntry = async (dir, value) => {
115
+ if (value) {
116
+ const entry = path.resolve(dir, value);
117
+ if (!await pathExists(entry)) throw new Error(`Entry file does not exist: ${entry}`);
118
+ return entry;
119
+ }
120
+ const tsEntry = path.join(dir, "index.ts");
121
+ if (await pathExists(tsEntry)) return tsEntry;
122
+ const tsxEntry = path.join(dir, "index.tsx");
123
+ if (await pathExists(tsxEntry)) return tsxEntry;
124
+ throw new Error(`Could not find index.ts or index.tsx inside ${dir}`);
125
+ };
126
+ const resolveEnv = (options) => ({
127
+ url: options.url ?? process.env.BASE_INTERNAL_URL ?? process.env.BASE_URL,
128
+ token: options.token ?? process.env.WM_TOKEN,
129
+ workspace: options.workspace ?? process.env.WM_WORKSPACE
130
+ });
131
+ const resolveProject = async (options = {}) => {
132
+ const dir = await resolveDir(options.dir);
133
+ const { path: config, root } = await resolveRoot(options.root, dir);
134
+ const wmillConfig = config ? await parseYamlFile(config) : {};
135
+ const pathValue = options.path ?? inferPath(dir, root);
136
+ const entry = await resolveEntry(dir, options.entry);
137
+ const { url, token, workspace } = resolveEnv(options);
138
+ return {
139
+ base: options.base ?? inferBase(pathValue),
140
+ config,
141
+ dir,
142
+ entry,
143
+ nonDotted: options.nonDotted ?? wmillConfig.nonDottedPaths ?? false,
144
+ path: pathValue,
145
+ root,
146
+ syncExcludes: wmillConfig.excludes ?? [],
147
+ ts: options.ts ?? wmillConfig.defaultTs ?? "bun",
148
+ workspace,
149
+ token,
150
+ url,
151
+ yaml: path.join(dir, RAW_APP_FILE_NAME)
152
+ };
153
+ };
154
+ const collectStaticFields = (fields) => Object.fromEntries(Object.entries(fields ?? {}).filter(([, field]) => field.type === "static").map(([name, field]) => [name, field.value]));
155
+ const createRawscriptHash = (content) => createHash("sha256").update(content ?? "").digest("hex");
156
+ const resolveTriggerableEntry = async (runnableId, runnable) => {
157
+ const staticInputs = collectStaticFields(runnable.fields);
158
+ const allowUserResources = Object.entries(runnable.fields ?? {}).filter(([, field]) => field.allowUserResources).map(([name]) => name);
159
+ if (runnable.inlineScript) return [`${runnableId}:rawscript/${createRawscriptHash(runnable.inlineScript.content)}`, {
160
+ allow_user_resources: allowUserResources,
161
+ one_of_inputs: {},
162
+ static_inputs: staticInputs
163
+ }];
164
+ if (runnable.path && runnable.runType) return [`${runnableId}:${runnable.runType === "hubscript" ? "script" : runnable.runType}/${runnable.path}`, {
165
+ allow_user_resources: allowUserResources,
166
+ one_of_inputs: {},
167
+ static_inputs: staticInputs
168
+ }];
169
+ };
170
+ const generateRawAppPolicy = async (runnables, policy, isPublic) => {
171
+ const resolvedTriggerableEntries = (await Promise.all(Object.entries(runnables).map(async ([runnableId, runnable]) => resolveTriggerableEntry(runnableId, runnable)))).filter((entry) => entry !== void 0);
172
+ return {
173
+ ...policy,
174
+ execution_mode: isPublic ? "anonymous" : "publisher",
175
+ triggerables_v2: Object.fromEntries(resolvedTriggerableEntries)
176
+ };
177
+ };
178
+ const resolveRunnableLanguage = (extension, ts) => {
179
+ const language = LANGUAGE_BY_EXTENSION[extension];
180
+ if (!language) return void 0;
181
+ return extension === "ts" ? ts : language;
182
+ };
183
+ const findRunnableContentFile = async (backendDir, runnableId, allFileNames) => {
184
+ for (const fileName of allFileNames) {
185
+ if (fileName.endsWith(".yaml") || fileName.endsWith(".lock")) continue;
186
+ if (!fileName.startsWith(`${runnableId}.`)) continue;
187
+ const extension = fileName.slice(runnableId.length + 1);
188
+ if (!resolveRunnableLanguage(extension, "bun")) continue;
189
+ return {
190
+ content: await readFile(path.join(backendDir, fileName), "utf8"),
191
+ extension
192
+ };
193
+ }
194
+ };
195
+ const getRunnableIdFromCodeFile = (fileName) => {
196
+ if (fileName.endsWith(".yaml") || fileName.endsWith(".lock")) return void 0;
197
+ for (const extension of Object.keys(LANGUAGE_BY_EXTENSION)) if (fileName.endsWith(`.${extension}`)) return fileName.slice(0, -(extension.length + 1));
198
+ };
199
+ const inlinePathPrefix = "!inline ";
200
+ const dereferenceInlineValue = async (value, localPath) => {
201
+ if (typeof value !== "string" || !value.startsWith(inlinePathPrefix)) return value;
202
+ const relativePath = value.slice(8);
203
+ return readFile(path.join(localPath, relativePath), "utf8");
204
+ };
205
+ const cloneRunnable = async (value, localPath) => {
206
+ if (Array.isArray(value)) return Promise.all(value.map(async (item) => cloneRunnable(item, localPath)));
207
+ if (typeof value !== "object" || value === null) return dereferenceInlineValue(value, localPath);
208
+ const entries = await Promise.all(Object.entries(value).map(async ([key, entryValue]) => [key, await cloneRunnable(entryValue, localPath)]));
209
+ return Object.fromEntries(entries);
210
+ };
211
+ const loadRunnablesFromBackend = async (backendDir, ts = "bun") => {
212
+ const runnables = {};
213
+ try {
214
+ const allFileNames = (await readdir(backendDir, { withFileTypes: true })).filter((entry) => entry.isFile()).map((entry) => entry.name);
215
+ const processedIds = /* @__PURE__ */ new Set();
216
+ for (const fileName of allFileNames) {
217
+ if (!fileName.endsWith(".yaml")) continue;
218
+ const runnableId = fileName.slice(0, -5);
219
+ processedIds.add(runnableId);
220
+ const runnable = await parseYamlFile(path.join(backendDir, fileName));
221
+ if (runnable.type === "inline") {
222
+ const contentFile = await findRunnableContentFile(backendDir, runnableId, allFileNames);
223
+ if (contentFile) {
224
+ const lockPath = path.join(backendDir, `${runnableId}.lock`);
225
+ let lock;
226
+ try {
227
+ lock = await readFile(lockPath, "utf8");
228
+ } catch (error) {
229
+ if (!isNodeError(error) || error.code !== "ENOENT") throw error;
230
+ }
231
+ runnable.inlineScript = {
232
+ ...runnable.inlineScript,
233
+ content: contentFile.content,
234
+ language: resolveRunnableLanguage(contentFile.extension, ts),
235
+ ...lock ? { lock } : {}
236
+ };
237
+ }
238
+ } else if (runnable.type === "flow" || runnable.type === "hubscript" || runnable.type === "script") {
239
+ const { type, schema: _schema, ...rest } = runnable;
240
+ runnables[runnableId] = {
241
+ ...rest,
242
+ runType: type,
243
+ type: "path"
244
+ };
245
+ continue;
246
+ }
247
+ runnables[runnableId] = runnable;
248
+ }
249
+ for (const fileName of allFileNames) {
250
+ const runnableId = getRunnableIdFromCodeFile(fileName);
251
+ if (!runnableId || processedIds.has(runnableId)) continue;
252
+ processedIds.add(runnableId);
253
+ const contentFile = await findRunnableContentFile(backendDir, runnableId, allFileNames);
254
+ if (!contentFile) continue;
255
+ const lockPath = path.join(backendDir, `${runnableId}.lock`);
256
+ let lock;
257
+ try {
258
+ lock = await readFile(lockPath, "utf8");
259
+ } catch (error) {
260
+ if (!isNodeError(error) || error.code !== "ENOENT") throw error;
261
+ }
262
+ runnables[runnableId] = {
263
+ inlineScript: {
264
+ content: contentFile.content,
265
+ language: resolveRunnableLanguage(contentFile.extension, ts),
266
+ ...lock ? { lock } : {}
267
+ },
268
+ type: "inline"
269
+ };
270
+ }
271
+ } catch (error) {
272
+ if (!isNodeError(error) || error.code !== "ENOENT") throw error;
273
+ }
274
+ return runnables;
275
+ };
276
+ const matchesSyncExclude = (relativePath, excludes) => excludes.some((pattern) => path.posix.matchesGlob(relativePath, pattern));
277
+ const collectAppFiles = async (dir, options = {}) => {
278
+ const files = {};
279
+ const root = options.root ? path.resolve(options.root) : dir;
280
+ const excludes = options.excludes ?? [];
281
+ const walk = async (currentDir, relativeDir = "/") => {
282
+ const entries = await readdir(currentDir, { withFileTypes: true });
283
+ for (const entry of entries) {
284
+ const fullPath = path.join(currentDir, entry.name);
285
+ const relativePath = `${relativeDir}${entry.name}`;
286
+ const relativeToRoot = normalizeToPosix(path.relative(root, fullPath));
287
+ if (entry.isDirectory()) {
288
+ if (DEPLOY_IGNORED_DIRECTORIES.has(entry.name)) continue;
289
+ await walk(fullPath, `${relativePath}/`);
290
+ continue;
291
+ }
292
+ if (DEPLOY_IGNORED_FILE_NAMES.has(entry.name)) continue;
293
+ if (matchesSyncExclude(relativeToRoot, excludes)) continue;
294
+ files[relativePath] = await readFile(fullPath, "utf8");
295
+ }
296
+ };
297
+ await walk(dir);
298
+ return files;
299
+ };
300
+ const loadRawAppProject = async (project) => {
301
+ const config = await parseYamlFile(project.yaml);
302
+ const backendDir = path.join(project.dir, "backend");
303
+ const backendRunnables = await loadRunnablesFromBackend(backendDir, project.ts);
304
+ const runnables = await cloneRunnable(Object.keys(backendRunnables).length > 0 ? backendRunnables : config.runnables ?? {}, backendDir);
305
+ const files = await collectAppFiles(project.dir, {
306
+ excludes: project.syncExcludes,
307
+ root: project.root
308
+ });
309
+ return {
310
+ config,
311
+ files,
312
+ policy: await generateRawAppPolicy(runnables, config.policy, Boolean(config.public)),
313
+ runnables,
314
+ value: {
315
+ ...config.data !== void 0 ? { data: config.data } : {},
316
+ files,
317
+ runnables
318
+ }
319
+ };
320
+ };
321
+ const createArgsType = (_runnable) => "{}";
322
+ const generateWmillDts = (runnables) => `// THIS FILE IS READ-ONLY
323
+ // AND GENERATED AUTOMATICALLY FROM YOUR RUNNABLES
324
+
325
+ export declare const backend: {
326
+ ${Object.entries(runnables).map(([name, runnable]) => ` ${name}: (args: ${createArgsType(runnable)}) => Promise<any>`).join("\n")}
327
+ }
328
+
329
+ export declare const backendAsync: {
330
+ ${Object.entries(runnables).map(([name, runnable]) => ` ${name}: (args: ${createArgsType(runnable)}) => Promise<string>`).join("\n")}
331
+ }
332
+
333
+ export type Job = {
334
+ type: 'QueuedJob' | 'CompletedJob'
335
+ id: string
336
+ created_at: number
337
+ started_at: number | undefined
338
+ duration_ms: number
339
+ success: boolean
340
+ args: any
341
+ result: any
342
+ }
343
+
344
+ export declare function waitJob(id: string): Promise<Job>
345
+ export declare function getJob(id: string): Promise<Job>
346
+
347
+ export type StreamUpdate = {
348
+ new_result_stream?: string
349
+ stream_offset?: number
350
+ }
351
+
352
+ export declare function streamJob(id: string, onUpdate?: (data: StreamUpdate) => void): Promise<any>
353
+ `;
354
+ const writeGeneratedWmillTypes = async (project) => {
355
+ const rawAppProject = await loadRawAppProject(project);
356
+ const filePath = path.join(project.dir, "wmill.d.ts");
357
+ const contents = generateWmillDts(rawAppProject.runnables);
358
+ await mkdir(path.dirname(filePath), { recursive: true });
359
+ await writeFile(filePath, contents);
360
+ };
361
+ //#endregion
362
+ //#region src/deploy.ts
363
+ const defaultDeploymentMessage = () => {
364
+ const sha = process.env.GITHUB_SHA;
365
+ return sha ? `vite-plugin-windmill deploy ${sha}` : "vite-plugin-windmill deploy";
366
+ };
367
+ const requireProjectConnection$1 = (project) => {
368
+ if (!project.workspace) throw new Error("Missing Windmill workspace. Set `workspace` or `WM_WORKSPACE`.");
369
+ if (!project.token) throw new Error("Missing Windmill token. Set `token` or `WM_TOKEN`.");
370
+ if (!project.url) throw new Error("Missing Windmill URL. Set `url`, `BASE_INTERNAL_URL`, or `BASE_URL`.");
371
+ return {
372
+ url: project.url,
373
+ token: project.token,
374
+ workspace: project.workspace
375
+ };
376
+ };
377
+ const readBundleFile = async (filePath, fallback = "") => {
378
+ try {
379
+ return await readFile(filePath, "utf8");
380
+ } catch (error) {
381
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return fallback;
382
+ throw error;
383
+ }
384
+ };
385
+ const readBundleContents = async (dir, js = path.join(dir, "dist/windmill/bundle.js"), css = path.join(dir, "dist/windmill/bundle.css")) => ({
386
+ css: await readBundleFile(css, ""),
387
+ js: await readBundleFile(js)
388
+ });
389
+ const findExistingRawApp = async (workspace, pathValue) => {
390
+ try {
391
+ return await AppService.getAppByPath({
392
+ workspace,
393
+ path: pathValue
394
+ });
395
+ } catch (error) {
396
+ if (error instanceof ApiError && error.status === 404) return void 0;
397
+ throw error;
398
+ }
399
+ };
400
+ /**
401
+ * Deploys a raw app to Windmill using `windmill-client` instead of shelling out to the CLI.
402
+ */
403
+ const deploy = async (options) => {
404
+ const dir = options.dir ?? process.cwd();
405
+ const project = await resolveProject({
406
+ ...options,
407
+ dir
408
+ });
409
+ const rawAppProject = await loadRawAppProject(project);
410
+ const connection = requireProjectConnection$1(project);
411
+ const bundles = options.bundles ?? await readBundleContents(dir, options.js, options.css);
412
+ if (!bundles.js) throw new Error("Cannot deploy a Windmill raw app without a JavaScript bundle");
413
+ if (options.dry) return {
414
+ action: "dry-run",
415
+ base: project.base,
416
+ path: project.path,
417
+ workspace: connection.workspace
418
+ };
419
+ setClient(connection.token, connection.url);
420
+ const existingApp = await findExistingRawApp(connection.workspace, project.path);
421
+ if (existingApp && !existingApp.raw_app) throw new Error(`${project.path} exists remotely but is not a raw app`);
422
+ const message = options.message ?? defaultDeploymentMessage();
423
+ const appPayload = {
424
+ ...rawAppProject.config.custom_path ? { custom_path: rawAppProject.config.custom_path } : {},
425
+ deployment_message: message,
426
+ path: project.path,
427
+ policy: rawAppProject.policy,
428
+ summary: rawAppProject.config.summary,
429
+ value: rawAppProject.value
430
+ };
431
+ if (existingApp) {
432
+ await AppService.updateAppRaw({
433
+ workspace: connection.workspace,
434
+ path: project.path,
435
+ formData: {
436
+ app: appPayload,
437
+ css: bundles.css,
438
+ js: bundles.js
439
+ }
440
+ });
441
+ return {
442
+ action: "update",
443
+ base: project.base,
444
+ path: project.path,
445
+ workspace: connection.workspace
446
+ };
447
+ }
448
+ await AppService.createAppRaw({
449
+ workspace: connection.workspace,
450
+ formData: {
451
+ app: appPayload,
452
+ css: bundles.css,
453
+ js: bundles.js
454
+ }
455
+ });
456
+ return {
457
+ action: "create",
458
+ base: project.base,
459
+ path: project.path,
460
+ workspace: connection.workspace
461
+ };
462
+ };
463
+ //#endregion
464
+ //#region src/dev-runtime-source.ts
465
+ const devRuntimeSource = String.raw`
466
+ const requestJson = async (path, body) => {
467
+ const response = await fetch(path, {
468
+ method: 'POST',
469
+ headers: { 'content-type': 'application/json' },
470
+ body: body ? JSON.stringify(body) : undefined,
471
+ })
472
+
473
+ const payload = await response.json()
474
+ if (!response.ok || payload.error) {
475
+ throw new Error(
476
+ payload.error ?? 'Windmill dev request failed with status ' + response.status,
477
+ )
478
+ }
479
+
480
+ return payload.result
481
+ }
482
+
483
+ export const backend = new Proxy(
484
+ {},
485
+ {
486
+ get(_, runnableId) {
487
+ return async (v) =>
488
+ requestJson('/__windmill__/backend', { runnableId, args: v ?? {} })
489
+ },
490
+ },
491
+ )
492
+
493
+ export const backendAsync = new Proxy(
494
+ {},
495
+ {
496
+ get(_, runnableId) {
497
+ return async (v) =>
498
+ requestJson('/__windmill__/backend-async', { runnableId, args: v ?? {} })
499
+ },
500
+ },
501
+ )
502
+
503
+ export const waitJob = async (jobId) => requestJson('/__windmill__/wait-job', { jobId })
504
+
505
+ export const getJob = async (jobId) => requestJson('/__windmill__/get-job', { jobId })
506
+
507
+ export const streamJob = async (jobId, onUpdate) =>
508
+ new Promise((resolve, reject) => {
509
+ const source = new EventSource(
510
+ '/__windmill__/stream-job/' + encodeURIComponent(jobId),
511
+ )
512
+
513
+ source.addEventListener('update', (event) => {
514
+ const data = JSON.parse(event.data)
515
+ onUpdate?.(data)
516
+ })
517
+
518
+ source.addEventListener('done', (event) => {
519
+ source.close()
520
+ resolve(JSON.parse(event.data))
521
+ })
522
+
523
+ source.addEventListener('error', (event) => {
524
+ source.close()
525
+ const message =
526
+ event instanceof MessageEvent && typeof event.data === 'string'
527
+ ? event.data
528
+ : 'Windmill stream request failed'
529
+ reject(new Error(message))
530
+ })
531
+ })
532
+ `;
533
+ //#endregion
534
+ //#region src/generated/upstream-build-runtime.ts
535
+ const buildRuntimeSource = "let reqs = {};\nfunction doRequest(type, o, extra) {\n return new Promise((resolve, reject) => {\n const reqId = Math.random().toString(36);\n reqs[reqId] = { resolve, reject, ...extra };\n const req = { ...o, type, reqId };\n parent.postMessage(req, '*');\n });\n}\nexport const backend = new Proxy({}, {\n get(_, runnable_id) {\n return (v) => {\n return doRequest('backend', { runnable_id, v });\n };\n }\n});\nexport const backendAsync = new Proxy({}, {\n get(_, runnable_id) {\n return (v) => {\n return doRequest('backendAsync', { runnable_id, v });\n };\n }\n});\nexport function waitJob(jobId) {\n return doRequest('waitJob', { jobId });\n}\nexport function getJob(jobId) {\n return doRequest('getJob', { jobId });\n}\n/**\n * Stream job results using SSE. Calls onUpdate for each stream update,\n * and resolves with the final result when the job completes.\n * @param jobId - The job ID to stream\n * @param onUpdate - Callback for stream updates with new_result_stream data\n * @returns Promise that resolves with the final job result\n */\nexport function streamJob(jobId, onUpdate) {\n return doRequest('streamJob', { jobId }, { onUpdate });\n}\nwindow.addEventListener('message', (e) => {\n if (e.data.type === 'streamJobUpdate') {\n // Handle streaming update\n let job = reqs[e.data.reqId];\n if (job && job.onUpdate) {\n job.onUpdate({\n new_result_stream: e.data.new_result_stream,\n stream_offset: e.data.stream_offset\n });\n }\n }\n else if (e.data.type === 'streamJobRes') {\n // Handle stream completion\n let job = reqs[e.data.reqId];\n if (job) {\n if (e.data.error) {\n job.reject(new Error(e.data.result?.stack ?? e.data.result?.message ?? 'Stream error'));\n }\n else {\n job.resolve(e.data.result);\n }\n delete reqs[e.data.reqId];\n }\n }\n else if (e.data.type === 'backendRes' ||\n e.data.type === 'backendAsyncRes' ||\n e.data.type === 'waitJobRes' ||\n e.data.type === 'getJobRes') {\n console.log('Message from parent backend', e.data);\n let job = reqs[e.data.reqId];\n if (job) {\n const result = e.data.result;\n if (e.data.error) {\n job.reject(new Error(result.stack ?? result.message));\n }\n else {\n job.resolve(result);\n }\n delete reqs[e.data.reqId];\n }\n else {\n console.error('No job found for', e.data.reqId);\n }\n }\n});\n";
536
+ //#endregion
537
+ //#region src/runtime.ts
538
+ const getWindmillRuntimeSource = (mode) => mode === "serve" ? devRuntimeSource : buildRuntimeSource;
539
+ //#endregion
540
+ //#region src/plugin.ts
541
+ const RESOLVED_VIRTUAL_WMILL_ID = `\0virtual:vite-plugin-windmill/wmill`;
542
+ const DEFAULT_BUILD_OUT_DIR = "dist/windmill";
543
+ const DEFAULT_API_PROXY_CONTEXT = "/api";
544
+ const DEPLOY_TRUE_VALUES = new Set([
545
+ "",
546
+ "1",
547
+ "on",
548
+ "true",
549
+ "yes"
550
+ ]);
551
+ const DEPLOY_FALSE_VALUES = new Set([
552
+ "0",
553
+ "false",
554
+ "no",
555
+ "off"
556
+ ]);
557
+ const DEPLOY_DRY_VALUES = new Set(["check", "dry"]);
558
+ const normalizePath = (value) => value.split(path.sep).join("/");
559
+ const buildHtmlDocument = (entryFile) => {
560
+ return `<!doctype html>
561
+ <html lang="en">
562
+ <head>
563
+ <meta charset="UTF-8" />
564
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
565
+ <title>Windmill Dev</title>
566
+ </head>
567
+ <body>
568
+ <div id="root"></div>
569
+ <script type="module" src="/@vite/client"><\/script>
570
+ <script type="module" src="${normalizePath(entryFile.startsWith("/") ? entryFile : `/${entryFile}`)}"><\/script>
571
+ </body>
572
+ </html>`;
573
+ };
574
+ const toErrorMessage = (value) => {
575
+ if (value instanceof Error) return value.message;
576
+ if (typeof value === "string") return value;
577
+ try {
578
+ return JSON.stringify(value);
579
+ } catch {
580
+ return "Unknown error";
581
+ }
582
+ };
583
+ const requireString = (value, fieldName) => {
584
+ if (typeof value === "string" && value.length > 0) return value;
585
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
586
+ throw new Error(`Missing or invalid ${fieldName}`);
587
+ };
588
+ const requireProjectConnection = (project) => {
589
+ if (!project.workspace) throw new Error("Missing Windmill workspace. Set `workspace` or `WM_WORKSPACE`.");
590
+ if (!project.token) throw new Error("Missing Windmill token. Set `token` or `WM_TOKEN`.");
591
+ if (!project.url) throw new Error("Missing Windmill URL. Set `url`, `BASE_INTERNAL_URL`, or `BASE_URL`.");
592
+ return {
593
+ url: project.url,
594
+ token: project.token,
595
+ workspace: project.workspace
596
+ };
597
+ };
598
+ const readJsonBody = async (request) => {
599
+ const chunks = [];
600
+ for await (const chunk of request) chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
601
+ if (chunks.length === 0) return {};
602
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
603
+ };
604
+ const waitForJobResult = async (workspace, jobId) => {
605
+ let delay = 50;
606
+ for (;;) {
607
+ const result = await JobService.getCompletedJobResultMaybe({
608
+ workspace,
609
+ id: jobId,
610
+ getStarted: false
611
+ });
612
+ if (result.completed) {
613
+ if (!result.success && typeof result.result === "object" && result.result && "error" in result.result) throw new Error(toErrorMessage(result.result.error));
614
+ return result.result;
615
+ }
616
+ await scheduler.wait(delay);
617
+ delay = delay >= 500 ? 2e3 : 500;
618
+ }
619
+ };
620
+ const executeRunnable = async (project, workspace, runnableId, runnable, args) => {
621
+ const requestBody = {
622
+ args: args ?? {},
623
+ component: runnableId,
624
+ force_viewer_allow_user_resources: Object.entries(runnable.fields ?? {}).filter(([, field]) => field.allowUserResources).map(([name]) => name),
625
+ force_viewer_one_of_fields: {},
626
+ force_viewer_static_fields: Object.fromEntries(Object.entries(runnable.fields ?? {}).filter(([, field]) => field.type === "static").map(([name, field]) => [name, field.value]))
627
+ };
628
+ if (runnable.inlineScript) {
629
+ requestBody.raw_code = {
630
+ cache_ttl: runnable.inlineScript.cache_ttl,
631
+ content: runnable.inlineScript.id === void 0 ? runnable.inlineScript.content ?? "" : "",
632
+ language: runnable.inlineScript.language ?? "",
633
+ lock: runnable.inlineScript.id === void 0 ? runnable.inlineScript.lock : void 0,
634
+ path: `${project.path}/${runnableId}`
635
+ };
636
+ if (runnable.inlineScript.id !== void 0) requestBody.id = runnable.inlineScript.id;
637
+ } else if (runnable.path && runnable.runType) requestBody.path = `${runnable.runType === "hubscript" ? "script" : runnable.runType}/${runnable.path}`;
638
+ else throw new Error(`Runnable ${runnableId} is missing inline or path metadata`);
639
+ return AppService.executeComponent({
640
+ workspace,
641
+ path: project.path,
642
+ requestBody
643
+ });
644
+ };
645
+ const extractBundleContents = (bundle) => {
646
+ let css = "";
647
+ let js = "";
648
+ for (const output of Object.values(bundle)) {
649
+ if (output.type === "chunk" && output.fileName === "bundle.js") js = output.code;
650
+ if (output.type === "asset" && output.fileName === "bundle.css") css = typeof output.source === "string" ? output.source : Buffer.from(output.source).toString("utf8");
651
+ }
652
+ return {
653
+ css,
654
+ js
655
+ };
656
+ };
657
+ const hasAuthorizationHeader = (headers) => Object.keys(headers ?? {}).some((key) => key.toLowerCase() === "authorization");
658
+ const resolveApiProxyConfig = (project, proxy) => {
659
+ if (proxy === false) return void 0;
660
+ const proxyOptions = proxy && typeof proxy === "object" ? { ...proxy } : void 0;
661
+ if (!(typeof proxy === "object" ? proxy.enabled ?? true : proxy ?? true)) return void 0;
662
+ const context = proxyOptions?.context ?? DEFAULT_API_PROXY_CONTEXT;
663
+ const target = proxyOptions?.target ?? project.url;
664
+ if (!target) return void 0;
665
+ const { context: _context, enabled: _enabled, target: _target, token, ...rest } = proxyOptions ?? {};
666
+ const headers = { ...rest.headers };
667
+ const resolvedToken = token ?? project.token;
668
+ if (!hasAuthorizationHeader(headers) && resolvedToken) headers.Authorization = `Bearer ${resolvedToken}`;
669
+ return { [context]: {
670
+ changeOrigin: rest.changeOrigin ?? true,
671
+ ...rest,
672
+ headers,
673
+ target
674
+ } };
675
+ };
676
+ const resolveProjectFromViteConfig = async (options, root, mode) => {
677
+ const env = loadEnv(mode, root ?? process.cwd(), "");
678
+ return resolveProject({
679
+ ...options,
680
+ dir: root ?? options.dir,
681
+ token: options.token ?? env.WM_TOKEN ?? process.env.WM_TOKEN,
682
+ url: options.url ?? env.BASE_INTERNAL_URL ?? env.BASE_URL ?? process.env.BASE_INTERNAL_URL ?? process.env.BASE_URL,
683
+ workspace: options.workspace ?? env.WM_WORKSPACE ?? process.env.WM_WORKSPACE
684
+ });
685
+ };
686
+ const normalizeDeployOptions = (deployOptions) => {
687
+ if (typeof deployOptions === "boolean") return { deploy: deployOptions };
688
+ if (!deployOptions) return void 0;
689
+ return {
690
+ deploy: deployOptions.deploy ?? true,
691
+ dry: deployOptions.dry,
692
+ message: deployOptions.message
693
+ };
694
+ };
695
+ const parseDeployEnv = (value) => {
696
+ if (value === void 0) return void 0;
697
+ const normalized = value.trim().toLowerCase();
698
+ if (normalized === "undefined" || normalized === "null") return void 0;
699
+ if (DEPLOY_TRUE_VALUES.has(normalized)) return { deploy: true };
700
+ if (DEPLOY_FALSE_VALUES.has(normalized)) return { deploy: false };
701
+ if (DEPLOY_DRY_VALUES.has(normalized)) return {
702
+ deploy: true,
703
+ dry: true
704
+ };
705
+ throw new Error(`Invalid WM_DEPLOY value \`${value}\`. Expected boolean-like values or \`dry\`.`);
706
+ };
707
+ const resolveDeployOptions = (options, root, mode) => {
708
+ const explicitDeploy = normalizeDeployOptions(options.deploy);
709
+ if (explicitDeploy) return explicitDeploy;
710
+ return parseDeployEnv(loadEnv(mode, root ?? process.cwd(), "").WM_DEPLOY ?? process.env.WM_DEPLOY) ?? { deploy: false };
711
+ };
712
+ /**
713
+ * Generates the HTML host shell for `vite preview`. It embeds the production IIFE bundle
714
+ * in a same-origin blob-URL iframe, mirroring how Windmill renders raw apps, and relays
715
+ * postMessage backend requests to the local /__windmill__/ HTTP proxy.
716
+ */
717
+ const buildPreviewHostShellHtml = (workspace) => `<!DOCTYPE html>
718
+ <html lang="en">
719
+ <head>
720
+ <meta charset="UTF-8" />
721
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
722
+ <title>Windmill Preview</title>
723
+ <style>html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden}iframe{position:fixed;inset:0;width:100%;height:100%;border:none}</style>
724
+ </head>
725
+ <body>
726
+ <iframe id="app" title="raw-app" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-downloads allow-modals allow-pointer-lock allow-presentation allow-storage-access-by-user-activation allow-top-navigation-by-user-activation"></iframe>
727
+ <script type="module">
728
+ window.localStorage.setItem('workspace', ${JSON.stringify(workspace)})
729
+
730
+ window.addEventListener('message', async ({ data: msg }) => {
731
+ if (!msg?.type || !msg?.reqId) return
732
+ const { type, reqId } = msg
733
+ const frame = document.getElementById('app')
734
+ const send = (result, error) =>
735
+ frame.contentWindow?.postMessage({ type: type + 'Res', reqId, result, error: !!error }, '*')
736
+
737
+ try {
738
+ if (type === 'backend' || type === 'backendAsync') {
739
+ const ep = type === 'backend' ? '/__windmill__/backend' : '/__windmill__/backend-async'
740
+ const r = await fetch(ep, {
741
+ method: 'POST',
742
+ headers: { 'content-type': 'application/json' },
743
+ body: JSON.stringify({ runnableId: msg.runnable_id, args: msg.v ?? {} }),
744
+ })
745
+ const p = await r.json()
746
+ send(p.result, !!p.error)
747
+ } else if (type === 'waitJob') {
748
+ const r = await fetch('/__windmill__/wait-job', {
749
+ method: 'POST',
750
+ headers: { 'content-type': 'application/json' },
751
+ body: JSON.stringify({ jobId: msg.jobId }),
752
+ })
753
+ const p = await r.json()
754
+ send(p.result, !!p.error)
755
+ } else if (type === 'getJob') {
756
+ const r = await fetch('/__windmill__/get-job', {
757
+ method: 'POST',
758
+ headers: { 'content-type': 'application/json' },
759
+ body: JSON.stringify({ jobId: msg.jobId }),
760
+ })
761
+ const p = await r.json()
762
+ send(p.result, !!p.error)
763
+ } else if (type === 'streamJob') {
764
+ const source = new EventSource('/__windmill__/stream-job/' + encodeURIComponent(msg.jobId))
765
+ source.addEventListener('update', (e) =>
766
+ frame.contentWindow?.postMessage({ type: 'streamJobUpdate', reqId, ...JSON.parse(e.data) }, '*'))
767
+ source.addEventListener('done', (e) => { source.close(); send(JSON.parse(e.data), false) })
768
+ source.addEventListener('error', () => { source.close(); send({ message: 'Stream error' }, true) })
769
+ }
770
+ } catch (err) {
771
+ send({ message: err?.message ?? String(err) }, true)
772
+ }
773
+ })
774
+
775
+ // Fetch the production bundle, wrap it in a blob URL, and load it into the iframe.
776
+ // Using a blob URL makes window.location.protocol === 'blob:' inside the iframe,
777
+ // which matches the production Windmill embedding behaviour.
778
+ const [cssRes, jsRes] = await Promise.all([fetch('/bundle.css'), fetch('/bundle.js')])
779
+ const [css, js] = await Promise.all([cssRes.text(), jsRes.text()])
780
+ const html = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8">'
781
+ + (css ? '<style>' + css + '</style>' : '')
782
+ + '</head><body><div id="root"></div><script>'
783
+ + js + '<\\/script></body></html>'
784
+ document.getElementById('app').src = URL.createObjectURL(new Blob([html], { type: 'text/html' }))
785
+ <\/script>
786
+ </body>
787
+ </html>`;
788
+ /**
789
+ * Creates a Vite plugin that aligns a SPA with Windmill raw-app build and deploy behavior.
790
+ */
791
+ const windmill = (options = {}) => {
792
+ let project;
793
+ let command = "serve";
794
+ let deployOptions = { deploy: false };
795
+ /**
796
+ * Shared Connect middleware that handles all /__windmill__/ API routes.
797
+ * Used by both the dev server and the preview server.
798
+ */
799
+ const windmillApiHandler = async (request, response, next) => {
800
+ try {
801
+ if (!project) return next();
802
+ const sendJson = (payload) => response.end(JSON.stringify(payload));
803
+ const connection = requireProjectConnection(project);
804
+ setClient(connection.token, connection.url);
805
+ if (request.url === "/__windmill__/backend" && request.method === "POST") {
806
+ try {
807
+ const body = await readJsonBody(request);
808
+ const rawAppProject = await loadRawAppProject(project);
809
+ const runnableId = requireString(body.runnableId, "runnableId");
810
+ const runnable = rawAppProject.runnables[runnableId];
811
+ if (!runnable) throw new Error(`Runnable not found: ${runnableId}`);
812
+ const jobId = await executeRunnable(project, connection.workspace, runnableId, runnable, body.args);
813
+ const result = await waitForJobResult(connection.workspace, jobId);
814
+ response.setHeader("content-type", "application/json");
815
+ sendJson({ result });
816
+ } catch (error) {
817
+ response.statusCode = 500;
818
+ response.setHeader("content-type", "application/json");
819
+ sendJson({ error: toErrorMessage(error) });
820
+ }
821
+ return;
822
+ }
823
+ if (request.url === "/__windmill__/backend-async" && request.method === "POST") {
824
+ try {
825
+ const body = await readJsonBody(request);
826
+ const rawAppProject = await loadRawAppProject(project);
827
+ const runnableId = requireString(body.runnableId, "runnableId");
828
+ const runnable = rawAppProject.runnables[runnableId];
829
+ if (!runnable) throw new Error(`Runnable not found: ${runnableId}`);
830
+ const jobId = await executeRunnable(project, connection.workspace, runnableId, runnable, body.args);
831
+ response.setHeader("content-type", "application/json");
832
+ sendJson({ result: jobId });
833
+ } catch (error) {
834
+ response.statusCode = 500;
835
+ response.setHeader("content-type", "application/json");
836
+ sendJson({ error: toErrorMessage(error) });
837
+ }
838
+ return;
839
+ }
840
+ if (request.url === "/__windmill__/wait-job" && request.method === "POST") {
841
+ try {
842
+ const body = await readJsonBody(request);
843
+ const result = await waitForJobResult(connection.workspace, requireString(body.jobId, "jobId"));
844
+ response.setHeader("content-type", "application/json");
845
+ sendJson({ result });
846
+ } catch (error) {
847
+ response.statusCode = 500;
848
+ response.setHeader("content-type", "application/json");
849
+ sendJson({ error: toErrorMessage(error) });
850
+ }
851
+ return;
852
+ }
853
+ if (request.url === "/__windmill__/get-job" && request.method === "POST") {
854
+ try {
855
+ const body = await readJsonBody(request);
856
+ const result = await JobService.getJob({
857
+ workspace: connection.workspace,
858
+ id: requireString(body.jobId, "jobId")
859
+ });
860
+ response.setHeader("content-type", "application/json");
861
+ sendJson({ result });
862
+ } catch (error) {
863
+ response.statusCode = 500;
864
+ response.setHeader("content-type", "application/json");
865
+ sendJson({ error: toErrorMessage(error) });
866
+ }
867
+ return;
868
+ }
869
+ if (request.url?.startsWith("/__windmill__/stream-job/") && request.method === "GET") {
870
+ try {
871
+ const jobId = decodeURIComponent(request.url.slice(25));
872
+ response.setHeader("cache-control", "no-cache");
873
+ response.setHeader("content-type", "text/event-stream");
874
+ response.setHeader("connection", "keep-alive");
875
+ const sseResponse = await fetch(`${connection.url.replace(/\/$/, "")}/api/w/${connection.workspace}/jobs_u/getupdate_sse/${jobId}?fast=true`, { headers: {
876
+ accept: "text/event-stream",
877
+ authorization: `Bearer ${connection.token}`
878
+ } });
879
+ if (!sseResponse.ok || !sseResponse.body) throw new Error(`Failed to stream Windmill job ${jobId}`);
880
+ const reader = Readable.fromWeb(sseResponse.body);
881
+ let buffer = "";
882
+ for await (const chunk of reader) {
883
+ buffer += chunk.toString();
884
+ const lines = buffer.split("\n");
885
+ buffer = lines.pop() ?? "";
886
+ for (const line of lines) {
887
+ if (!line.startsWith("data: ")) continue;
888
+ const payload = JSON.parse(line.slice(6));
889
+ if (payload.type === "ping") continue;
890
+ if (payload.type === "timeout") {
891
+ response.write(`event: error\ndata: ${JSON.stringify("Stream timed out")}\n\n`);
892
+ response.end();
893
+ return;
894
+ }
895
+ if (payload.type === "error") {
896
+ response.write(`event: error\ndata: ${JSON.stringify(payload.error ?? "Stream error")}\n\n`);
897
+ response.end();
898
+ return;
899
+ }
900
+ if (payload.new_result_stream !== void 0) response.write(`event: update\ndata: ${JSON.stringify({
901
+ new_result_stream: payload.new_result_stream,
902
+ stream_offset: payload.stream_offset
903
+ })}\n\n`);
904
+ if (payload.completed) {
905
+ response.write(`event: done\ndata: ${JSON.stringify(payload.only_result)}\n\n`);
906
+ response.end();
907
+ return;
908
+ }
909
+ }
910
+ }
911
+ response.end();
912
+ } catch (error) {
913
+ response.write(`event: error\ndata: ${JSON.stringify(toErrorMessage(error))}\n\n`);
914
+ response.end();
915
+ }
916
+ return;
917
+ }
918
+ next();
919
+ } catch (error) {
920
+ next(error);
921
+ }
922
+ };
923
+ return {
924
+ name: "vite-plugin-windmill",
925
+ async config(userConfig, env) {
926
+ project = await resolveProjectFromViteConfig(options, userConfig.root, env.mode);
927
+ command = env.command;
928
+ deployOptions = resolveDeployOptions(options, userConfig.root, env.mode);
929
+ const isServe = env.command === "serve";
930
+ const apiProxy = resolveApiProxyConfig(project, options.proxy);
931
+ return {
932
+ appType: "custom",
933
+ base: isServe ? "/" : project.base,
934
+ build: {
935
+ chunkSizeWarningLimit: 2048,
936
+ outDir: DEFAULT_BUILD_OUT_DIR,
937
+ ...isServe ? {} : {
938
+ assetsInlineLimit: Number.MAX_SAFE_INTEGER,
939
+ cssCodeSplit: false,
940
+ modulePreload: false,
941
+ reportCompressedSize: false,
942
+ rolldownOptions: {
943
+ input: project.entry,
944
+ output: {
945
+ assetFileNames: (assetInfo) => assetInfo.name?.endsWith(".css") ? "bundle.css" : "assets/[name]-[hash][extname]",
946
+ entryFileNames: "bundle.js",
947
+ format: "iife"
948
+ }
949
+ }
950
+ }
951
+ },
952
+ ...isServe ? { publicDir: false } : {},
953
+ define: { "process.env.NODE_ENV": JSON.stringify(isServe ? "development" : "production") },
954
+ preview: {
955
+ open: false,
956
+ ...apiProxy ? { proxy: apiProxy } : {}
957
+ },
958
+ server: {
959
+ open: false,
960
+ ...apiProxy ? { proxy: apiProxy } : {}
961
+ }
962
+ };
963
+ },
964
+ async configResolved(resolvedConfig) {
965
+ project = await resolveProjectFromViteConfig(options, resolvedConfig.root, resolvedConfig.mode);
966
+ deployOptions = resolveDeployOptions(options, resolvedConfig.root, resolvedConfig.mode);
967
+ await writeGeneratedWmillTypes(project);
968
+ },
969
+ resolveId(id) {
970
+ if (WMILL_IMPORT_PATTERN.test(id)) return RESOLVED_VIRTUAL_WMILL_ID;
971
+ },
972
+ load(id) {
973
+ if (id === RESOLVED_VIRTUAL_WMILL_ID) return getWindmillRuntimeSource(command);
974
+ },
975
+ configurePreviewServer(previewServer) {
976
+ return () => {
977
+ const previewHandler = async (request, response, next) => {
978
+ if (!project) return next();
979
+ const acceptsHtml = request.headers.accept?.includes("text/html") ?? false;
980
+ const url = request.url ?? "/";
981
+ if (request.method === "GET" && !url.startsWith("/__windmill__/") && (acceptsHtml || !path.extname(url) && !url.includes("?"))) {
982
+ if (!project.workspace) throw new Error("Missing Windmill workspace. Set `workspace` or `WM_WORKSPACE`.");
983
+ response.setHeader("content-type", "text/html");
984
+ response.end(buildPreviewHostShellHtml(project.workspace));
985
+ return;
986
+ }
987
+ return Promise.resolve(windmillApiHandler(request, response, next)).catch(next);
988
+ };
989
+ previewServer.middlewares.use((req, res, next) => Promise.resolve(previewHandler(req, res, next)).catch(next));
990
+ };
991
+ },
992
+ configureServer(configuredServer) {
993
+ return () => {
994
+ const handler = async (request, response, next) => {
995
+ try {
996
+ if (!project) return next();
997
+ if (request.url?.startsWith("/__windmill__/")) return Promise.resolve(windmillApiHandler(request, response, next)).catch(next);
998
+ const url = request.url ?? "/";
999
+ if (request.method === "GET" && !path.extname(url) && !url.includes("?")) {
1000
+ const entryRelative = normalizePath(path.relative(project.dir, project.entry));
1001
+ const html = await configuredServer.transformIndexHtml(url, buildHtmlDocument(entryRelative));
1002
+ response.setHeader("content-type", "text/html");
1003
+ response.end(html);
1004
+ return;
1005
+ }
1006
+ next();
1007
+ } catch (error) {
1008
+ next(error);
1009
+ }
1010
+ };
1011
+ configuredServer.middlewares.use((req, res, next) => Promise.resolve(handler(req, res, next)).catch(next));
1012
+ };
1013
+ },
1014
+ async handleHotUpdate(context) {
1015
+ if (!project) return;
1016
+ if (context.file.startsWith(path.join(project.dir, "backend")) || context.file === project.yaml) {
1017
+ await writeGeneratedWmillTypes(project);
1018
+ context.server.ws.send({ type: "full-reload" });
1019
+ return;
1020
+ }
1021
+ },
1022
+ async writeBundle(_outputOptions, bundle) {
1023
+ if (!project) return;
1024
+ if (!deployOptions.deploy) return;
1025
+ const result = await deploy({
1026
+ base: project.base,
1027
+ bundles: extractBundleContents(bundle),
1028
+ dir: project.dir,
1029
+ dry: deployOptions.dry,
1030
+ message: deployOptions.message ?? options.message,
1031
+ path: project.path,
1032
+ root: project.root,
1033
+ token: project.token,
1034
+ url: project.url,
1035
+ workspace: project.workspace
1036
+ });
1037
+ this.info(result.action === "dry-run" ? `Windmill deploy dry-run ready for ${result.path}` : `Windmill raw app ${result.action}d: ${result.path}`);
1038
+ }
1039
+ };
1040
+ };
1041
+ //#endregion
1042
+ export { windmill as default, windmill, deploy };
1043
+
1044
+ //# sourceMappingURL=index.mjs.map