Files
windmill/cli/src/utils/resource_folders.ts
T
Ruben FiszelandClaude Opus 4.6 31d6660d56 feat: script module mode with CLI sync, preview, and WAC UI improvements (#8380)
* feat: add script module mode with folder model for Bun and Python

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add missing modules field to RawCode in bun_executor

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* sqlx

* feat: enrich WAC templates with checkpoint and replay semantics

Add prominent comments explaining that all computation must happen
inside task/step/taskScript or it will be replayed on resume/retry.
Clarify that waitForApproval does not hold a worker and that
approve/reject URLs are available in the timeline step details.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(cli): script module sync idempotency, per-module hash tracking, and preview support

- Fix pull→push idempotency: use `??` instead of `||` for module lock
  field so empty strings are preserved (matches API's `lock: ""`)
- Add per-module hash tracking in wmill-lock.yaml following the flow
  inline script pattern (SCRIPT_TOP_HASH + per-module subpath hashes)
- Selective module lock regeneration: only regenerate locks for modules
  whose content actually changed, not all modules
- Use unfiltered rawWorkspaceDependencies for module hashes to match
  what updateModuleLocks passes to fetchScriptLock
- Show changed module names in stale script output for clarity
- Add module support to `script preview` command: read modules from
  __mod/ folder and pass them in the preview API request
- Add preview tests for taskScript pattern (flat and folder layout)
- Update test assertion for module stale detection output

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(frontend): WAC UI improvements — reorder templates, module tab rename, import consolidation

- Reorder WAC template buttons: TypeScript before Python in
  ScriptBuilder, CreateActionsScript, and CreateActionsFlow
- Remove dropdown items from +Script button (simplify to direct link)
- Move "Import Workflow-as-Code" to +Flow dropdown with dedicated drawer
- Add module tab rename: pencil icon on hover opens popover with
  validation, fixed-width icon container prevents layout shift

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: remaining module-mode changes from working branch

- Backend parser updates for WAC detection
- CLI sync/types updates for raw app path and module support
- Frontend UI polish (Dev.svelte, ScriptRow, script hash page)
- Test fixture updates

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test(cli): add test for module modification detection in generate-metadata

Verifies that modifying a single module file re-triggers stale
detection and only the changed module is listed, not all modules.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): critical fixes from PR review

- Fix hardcoded dev path in bun_executor.rs WAC v2 wrapper — use
  "windmill-client" import instead of absolute filesystem path
- Fix missed no_main_func → auto_kind rename in parser TS test
- Add modules column to clone_script SQL (windmill-common and
  windmill-api-workspaces) so cloned scripts retain their modules
- Add modules: None to RawCode structs in worker tests
- Restore complete sqlx cache (merge main's cache + our new queries)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix clone warning treated as error in CI

Change `.clone()` on double reference to `*k` dereference in
scripts.rs hash implementation. Update sqlx cache with new query
hashes from modified clone_script SQL.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): use published parser wasm versions for CI build

The local file:// paths for windmill-parser-wasm-py and
windmill-parser-wasm-ts don't exist in the Cloudflare Pages build
environment. Revert to published npm versions (1.655.0).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): update parser wasm packages to 1.657.2

Use newly published windmill-parser-wasm-ts and windmill-parser-wasm-py
v1.657.2 which include auto_kind/WAC detection changes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): regenerate package-lock.json for npm ci compatibility

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): use main's lockfile as base, update only parser wasm packages

Regenerating package-lock.json from scratch pulled different dependency
versions causing svelte-check type errors. Instead, start from main's
lockfile and only update the two changed packages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): add modules column to fetch_script_for_update query

The Script<SR> struct has a modules field (FromRow), but
fetch_script_for_update didn't SELECT modules, causing a runtime
error "no column found for name: modules" when the worker processed
dependency jobs. This was the root cause of the relock_skip test
timeout.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix script module execution for Python and Bun

- Fix modules not passed through job queue: inject _MODULES into
  PushArgs.extra when pushing Code jobs so worker can extract them
- Fix Python module imports: use relative imports (from .helper)
  and add sys.path.insert for module directory in wrapper
- Fix Python tests: use relative imports and empty lock to prevent
  pip from resolving module names as packages
- Add local file check in Bun loader for module resolution
- Ignore Bun module test (bundle mode loader integration tracked
  separately)
- Add missing modules column to fetch_script_for_update query

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): remove unnecessary empty lock in Python module tests

Relative imports (from .helper) are not parsed as pip packages,
so the empty lock workaround is not needed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix module execution for Python and Bun — all tests pass

Python modules:
- Use relative imports (from .helper import greet) since scripts run
  as packages
- Add sys.path.insert for module directory in wrapper to ensure local
  modules take precedence over pip packages with same name

Bun modules:
- Use bundled output (./out/main.js) as wrapper import when modules
  are present — the bundled output has module content inlined by
  Bun.build, avoiding runtime loader resolution issues
- Add local file check in loader.bun.js onResolve to short-circuit
  API URL resolution for module files on disk

Job queue:
- Inject _MODULES into PushArgs.extra when pushing Code jobs so
  the worker can extract them at execution time

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: address PR review — simplify, fix correctness, remove dead code

Critical fixes:
- Replace all CLI `no_main_func` references with `auto_kind` (string)
  to match the backend migration and API changes
- Remove duplicated `compute_python_module_dir` in worker.rs, use
  the canonical version from python_executor.rs

High priority:
- Auto-create `__init__.py` in intermediate directories for nested
  Python modules so imports like `from .utils.math import add` work
  without users manually creating __init__.py files
- Remove redundant `sys_path_insert` — relative imports use Python's
  package system, not sys.path

Medium:
- Fix lock file base name extraction: use regex to strip only the
  final extension (`.replace(/\.[^.]+$/, '')`) instead of `indexOf(".")`
  which breaks for files like `helper.test.ts`

Simplification:
- Remove dead `{#if false}` Popover block in ScriptEditor.svelte
- Guard loader.bun.js local file check to only run for relative paths
  (matching the Windows loader pattern)
- Add clarifying comment on Bun dual mechanism (build + run phases)
- Add maintenance comment on manual Hash impl for NewScript

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: final review fixes — stale cleanup, baseName, auto_kind export

- Fix sync.ts baseName extraction using indexOf(".") → regex
  (same fix as script.ts/metadata.ts, missed this instance)
- Add stale module file cleanup in writeModulesToDisk: removes files
  from __mod/ that are no longer in the modules map before writing,
  fixing the pull→push cycle that couldn't delete modules
- Log warning when _MODULES serialization fails in job push instead
  of silently dropping modules
- Use strict equality (===) for auto_kind comparison
- Exclude auto_kind from workspace export — it is auto-detected by
  the parser at deploy time from script content

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(cli): remove auto_kind from push, comparison, and metadata

auto_kind is auto-detected by the parser at deploy time, so the CLI
should not send it, compare it, or write it to script.yaml.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: remove erroneously added backend/backend/.sqlx directory

Duplicate .sqlx cache was committed at the wrong nested path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review feedback + fix CI dead_code warning

Frontend (ScriptEditor.svelte):
- Fix switchToMain() missing lastSyncedCode update — prevents stale
  code sync on external changes while editing a module tab
- Fix formatAction saving module code to main script's localStorage
  draft — now saves main code when on a module tab
- Fix non-null assertion on inferModuleLang in renameModule — fall
  back to original language instead of force unwrap
- Remove redundant activeModuleTab truthy check in runTest

CLI (script.ts):
- Clean up empty directories after removing stale module files in
  writeModulesToDisk

Backend:
- Add path traversal guard in write_module_files — reject module
  paths containing ".."
- Fix dead_code warning on auto_kind field in workspace export struct

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(frontend): improve auto_kind UX + address review findings

- Rename "Include without main function" toggle to "Include library
  scripts" in script list (ItemsList.svelte)
- Update NoMainFuncBadge: "No main" → "Library" with clearer tooltip
- Filter module file extensions by main script language — Python
  scripts only allow .py modules, TypeScript only .ts, etc.
- Split flushModuleState into flushModuleContent (no UI side-effect)
  and flushModuleState (flush + reset tab), reducing duplication
- Dynamic placeholder and hint text in add module popover based on
  main script language

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 01:20:09 +00:00

537 lines
17 KiB
TypeScript

/**
* Utility module for handling resource folder naming conventions.
*
* This module centralizes the logic for detecting and manipulating paths
* that contain resource folders (.flow, .app, .raw_app).
*
* The folder suffixes can be configured to use either dot-prefixed names
* (.flow, .app, .raw_app) or dunder-prefixed names (__flow, __app, __raw_app).
*/
import * as log from "../core/log.ts";
import { sep as SEP } from "node:path";
import { yamlParseFile } from "./yaml.ts";
import * as fs from "node:fs";
import * as path from "node:path";
import process from "node:process";
// Resource types that use folder-based storage
export type FolderResourceType = "flow" | "app" | "raw_app";
// Configuration for folder suffixes - can be switched between dot and dunder prefixes
// The default uses dot-prefixed names (.flow, .app, .raw_app)
const DOTTED_SUFFIXES = {
flow: ".flow",
app: ".app",
raw_app: ".raw_app",
} as const;
// Alternative dunder-prefixed names (__flow, __app, __raw_app)
const NON_DOTTED_SUFFIXES = {
flow: "__flow",
app: "__app",
raw_app: "__raw_app",
} as const;
export type FolderSuffixes =
| typeof DOTTED_SUFFIXES
| typeof NON_DOTTED_SUFFIXES;
// Global state for nonDottedPaths configuration
let _nonDottedPaths = false;
let _nonDottedPathsLogged = false;
/**
* Set whether to use non-dotted paths (__flow, __app, __raw_app)
* instead of dotted paths (.flow, .app, .raw_app).
* This should be called once at startup based on wmill.yaml configuration.
*/
export function setNonDottedPaths(value: boolean): void {
if (value && !_nonDottedPathsLogged) {
log.info("Using non-dotted paths (__flow, __app, __raw_app)");
_nonDottedPathsLogged = true;
}
_nonDottedPaths = value;
}
/**
* Get the current nonDottedPaths setting.
*/
export function getNonDottedPaths(): boolean {
return _nonDottedPaths;
}
/**
* Search for wmill.yaml by traversing upward from the current directory
* and initialize the nonDottedPaths setting.
* Unlike findWmillYaml() in conf.ts, this does not stop at the git root -
* it continues searching until the filesystem root.
* This is needed for commands like `app dev` and `app new` which may run
* from inside folders that are deeply nested within a larger git repository.
*/
export async function loadNonDottedPathsSetting(): Promise<void> {
let currentDir = process.cwd();
while (true) {
const wmillYamlPath = path.join(currentDir, "wmill.yaml");
if (fs.existsSync(wmillYamlPath)) {
try {
const config = (await yamlParseFile(wmillYamlPath)) as {
nonDottedPaths?: boolean;
};
setNonDottedPaths(config?.nonDottedPaths ?? false);
log.debug(
`Found wmill.yaml at ${wmillYamlPath}, nonDottedPaths=${
config?.nonDottedPaths ?? false
}`
);
} catch (e) {
log.debug(`Failed to parse wmill.yaml at ${wmillYamlPath}: ${e}`);
}
return;
}
// Check if we've reached the filesystem root
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
// Reached filesystem root without finding wmill.yaml
log.debug("No wmill.yaml found, using default dotted paths");
return;
}
currentDir = parentDir;
}
}
/**
* Get the folder suffixes based on the global configuration.
*/
export function getFolderSuffixes(): FolderSuffixes {
return _nonDottedPaths ? NON_DOTTED_SUFFIXES : DOTTED_SUFFIXES;
}
// Metadata file names inside each folder type
const METADATA_FILES = {
flow: { yaml: "flow.yaml", json: "flow.json" },
app: { yaml: "app.yaml", json: "app.json" },
raw_app: { yaml: "raw_app.yaml", json: "raw_app.json" },
} as const;
/**
* Get the folder suffix for a resource type (e.g., ".flow", ".app", ".raw_app" or "__flow", "__app", "__raw_app")
*/
export function getFolderSuffix(type: FolderResourceType): string {
return getFolderSuffixes()[type];
}
/**
* Get the folder suffix with path separator (e.g., ".flow/", ".app/", ".raw_app/")
*/
export function getFolderSuffixWithSep(type: FolderResourceType): string {
return getFolderSuffixes()[type] + SEP;
}
/**
* Get the metadata file name for a resource type
*/
export function getMetadataFileName(
type: FolderResourceType,
format: "yaml" | "json"
): string {
return METADATA_FILES[type][format];
}
/**
* Get the full metadata file path suffix (e.g., ".flow/flow.yaml" or "__flow/flow.yaml")
*/
export function getMetadataPathSuffix(
type: FolderResourceType,
format: "yaml" | "json"
): string {
return getFolderSuffixes()[type] + "/" + METADATA_FILES[type][format];
}
// ============================================================================
// Path Detection Functions
// ============================================================================
/** Normalize path separators to forward slash for cross-platform matching */
function normalizeSep(p: string): string {
return p.replaceAll("\\", "/");
}
/**
* Check if a path is inside a flow folder
*/
export function isFlowPath(p: string): boolean {
return normalizeSep(p).includes(getFolderSuffixes().flow + "/");
}
/**
* Check if a path is inside an app folder
*/
export function isAppPath(p: string): boolean {
return normalizeSep(p).includes(getFolderSuffixes().app + "/");
}
/**
* Check if a path is inside a raw_app folder
*/
export function isRawAppPath(p: string): boolean {
return normalizeSep(p).includes(getFolderSuffixes().raw_app + "/");
}
/**
* Check if a path is inside any folder-based resource (flow, app, or raw_app)
*/
export function isFolderResourcePath(p: string): boolean {
return isFlowPath(p) || isAppPath(p) || isRawAppPath(p);
}
/**
* Detect the resource type from a path, if any
*/
export function detectFolderResourceType(p: string): FolderResourceType | null {
if (isFlowPath(p)) return "flow";
if (isAppPath(p)) return "app";
if (isRawAppPath(p)) return "raw_app";
return null;
}
/**
* Check if a path is inside a raw app backend folder.
* Matches patterns like: .../myApp.raw_app/backend/... or .../myApp__raw_app/backend/...
*/
export function isRawAppBackendPath(filePath: string): boolean {
const suffixes = getFolderSuffixes();
// Normalize path separators for consistent matching
const normalizedPath = filePath.replaceAll(SEP, "/");
// Check if path contains pattern: *.[suffix]/backend/
const escapedSuffix = suffixes.raw_app.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`${escapedSuffix}/backend/`);
return pattern.test(normalizedPath);
}
/**
* Check if a path is inside a normal app folder (inline script).
* Matches patterns like: .../myApp.app/... or .../myApp__app/...
* This is used to detect inline scripts that belong to normal apps.
*/
export function isAppInlineScriptPath(filePath: string): boolean {
const suffixes = getFolderSuffixes();
// Normalize path separators for consistent matching
const normalizedPath = filePath.replaceAll(SEP, "/");
// Check if path contains pattern: *.[suffix]/
const escapedSuffix = suffixes.app.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`${escapedSuffix}/`);
return pattern.test(normalizedPath);
}
/**
* Check if a path is inside a flow folder (inline script).
* Matches patterns like: .../myFlow.flow/... or .../myFlow__flow/...
* This is used to detect inline scripts that belong to flows.
*/
export function isFlowInlineScriptPath(filePath: string): boolean {
const suffixes = getFolderSuffixes();
// Normalize path separators for consistent matching
const normalizedPath = filePath.replaceAll(SEP, "/");
// Check if path contains pattern: *.[suffix]/
const escapedSuffix = suffixes.flow.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(`${escapedSuffix}/`);
return pattern.test(normalizedPath);
}
// ============================================================================
// Path Manipulation Functions
// ============================================================================
/**
* Extract the resource name from a path (the part before the folder suffix)
* e.g., "f/my_flow.flow/flow.yaml" -> "f/my_flow"
*/
export function extractResourceName(
p: string,
type: FolderResourceType
): string | null {
const normalized = normalizeSep(p);
const suffix = getFolderSuffixes()[type] + "/";
const index = normalized.indexOf(suffix);
if (index === -1) return null;
return normalized.substring(0, index);
}
/**
* Extract the folder path (resource name + folder suffix)
* e.g., "f/my_flow.flow/flow.yaml" -> "f/my_flow.flow/"
*/
export function extractFolderPath(
p: string,
type: FolderResourceType
): string | null {
const normalized = normalizeSep(p);
const suffix = getFolderSuffixes()[type] + "/";
const index = normalized.indexOf(suffix);
if (index === -1) return null;
return normalized.substring(0, index) + suffix;
}
/**
* Build a folder path from a resource name
* e.g., ("f/my_flow", "flow") -> "f/my_flow.flow"
*/
export function buildFolderPath(
resourceName: string,
type: FolderResourceType
): string {
return resourceName + getFolderSuffixes()[type];
}
/**
* Build a metadata file path from a resource name
* e.g., ("f/my_flow", "flow", "yaml") -> "f/my_flow.flow/flow.yaml"
*/
export function buildMetadataPath(
resourceName: string,
type: FolderResourceType,
format: "yaml" | "json"
): string {
return (
resourceName +
getFolderSuffixes()[type] +
"/" +
METADATA_FILES[type][format]
);
}
// ============================================================================
// Folder Validation Functions
// ============================================================================
/**
* Check if a directory name ends with a specific resource folder suffix
* e.g., "my_app.raw_app" ends with ".raw_app" or "my_app__raw_app" ends with "__raw_app"
*/
export function hasFolderSuffix(
dirName: string,
type: FolderResourceType
): boolean {
return dirName.endsWith(getFolderSuffixes()[type]);
}
/**
* Validate that a directory name has the expected folder suffix
* Returns an error message if invalid, null if valid
*/
export function validateFolderName(
dirName: string,
type: FolderResourceType
): string | null {
const suffixes = getFolderSuffixes();
if (!hasFolderSuffix(dirName, type)) {
return `'${dirName}' does not end with '${suffixes[type]}'`;
}
return null;
}
/**
* Extract the resource name from a folder name by removing the suffix
* e.g., "my_app.raw_app" -> "my_app" or "my_app__raw_app" -> "my_app"
*/
export function extractNameFromFolder(
folderName: string,
type: FolderResourceType
): string {
const suffix = getFolderSuffixes()[type];
if (folderName.endsWith(suffix)) {
return folderName.substring(0, folderName.length - suffix.length);
}
return folderName;
}
// ============================================================================
// Metadata File Detection Functions
// ============================================================================
/**
* Check if a path ends with a flow metadata file suffix.
* Detects BOTH API format (always dotted: .flow.json) and local format (user-configured).
* This is necessary because the API always returns dotted format, but local files
* may use non-dotted format if nonDottedPaths is configured.
*/
export function isFlowMetadataFile(p: string): boolean {
// Always check API format (dotted)
if (
p.endsWith(DOTTED_SUFFIXES.flow + ".json") ||
p.endsWith(DOTTED_SUFFIXES.flow + ".yaml")
) {
return true;
}
// Also check non-dotted format for local files
if (_nonDottedPaths) {
return (
p.endsWith(NON_DOTTED_SUFFIXES.flow + ".json") ||
p.endsWith(NON_DOTTED_SUFFIXES.flow + ".yaml")
);
}
return false;
}
/**
* Check if a path ends with an app metadata file suffix.
* Detects BOTH API format (always dotted: .app.json) and local format (user-configured).
*/
export function isAppMetadataFile(p: string): boolean {
// Always check API format (dotted)
if (
p.endsWith(DOTTED_SUFFIXES.app + ".json") ||
p.endsWith(DOTTED_SUFFIXES.app + ".yaml")
) {
return true;
}
// Also check non-dotted format for local files
if (_nonDottedPaths) {
return (
p.endsWith(NON_DOTTED_SUFFIXES.app + ".json") ||
p.endsWith(NON_DOTTED_SUFFIXES.app + ".yaml")
);
}
return false;
}
/**
* Check if a path ends with a raw_app metadata file suffix.
* Detects BOTH API format (always dotted: .raw_app.json) and local format (user-configured).
*/
export function isRawAppMetadataFile(p: string): boolean {
// Always check API format (dotted)
if (
p.endsWith(DOTTED_SUFFIXES.raw_app + ".json") ||
p.endsWith(DOTTED_SUFFIXES.raw_app + ".yaml")
) {
return true;
}
// Also check non-dotted format for local files
if (_nonDottedPaths) {
return (
p.endsWith(NON_DOTTED_SUFFIXES.raw_app + ".json") ||
p.endsWith(NON_DOTTED_SUFFIXES.raw_app + ".yaml")
);
}
return false;
}
/**
* Check if a path ends with a specific raw_app metadata file
* (inside the folder, e.g., ".raw_app/raw_app.yaml" or "__raw_app/raw_app.yaml")
*/
export function isRawAppFolderMetadataFile(p: string): boolean {
return (
p.endsWith(getMetadataPathSuffix("raw_app", "yaml")) ||
p.endsWith(getMetadataPathSuffix("raw_app", "json"))
);
}
// ============================================================================
// Script Module Path Functions
// ============================================================================
/**
* The suffix used for script module folders.
* Unlike flows/apps, modules always use `__mod` (never dotted `.mod`)
* to avoid confusion with file extensions.
*/
const MODULE_SUFFIX = "__mod";
/**
* Get the module folder suffix (always "__mod")
*/
export function getModuleFolderSuffix(): string {
return MODULE_SUFFIX;
}
/**
* Check if a path is inside a script module folder.
* Matches patterns like: .../my_script__mod/...
*/
export function isScriptModulePath(p: string): boolean {
return normalizeSep(p).includes(MODULE_SUFFIX + "/");
}
/**
* Build the module folder path from a script's base path (without extension).
* e.g., "f/my_script" -> "f/my_script__mod"
*/
export function buildModuleFolderPath(scriptBasePath: string): string {
return scriptBasePath + MODULE_SUFFIX;
}
/**
* Check if a file inside a __mod/ folder is the main entry point (script.{ext}).
* Entry points are files named "script.*" directly under __mod/ (not in subdirs).
*/
export function isModuleEntryPoint(p: string): boolean {
const norm = normalizeSep(p);
const suffix = MODULE_SUFFIX + "/";
const idx = norm.indexOf(suffix);
if (idx === -1) return false;
const rest = norm.slice(idx + suffix.length);
return rest.startsWith("script.") && !rest.includes("/");
}
/**
* Extract the script base path from a module folder entry.
* e.g., "u/admin/my_script__mod/script.ts" -> "u/admin/my_script"
* e.g., "u/admin/my_script__mod/helper.ts" -> "u/admin/my_script"
*/
export function getScriptBasePathFromModulePath(p: string): string | undefined {
const norm = normalizeSep(p);
const suffix = MODULE_SUFFIX + "/";
const idx = norm.indexOf(suffix);
if (idx === -1) return undefined;
return norm.slice(0, idx);
}
// ============================================================================
// Sync-related Path Functions
// ============================================================================
/**
* Get the path suffix to remove when converting local path to API path
* for delete operations
*/
export function getDeleteSuffix(
type: FolderResourceType,
format: "yaml" | "json"
): string {
return getFolderSuffixes()[type] + "/" + METADATA_FILES[type][format];
}
/**
* Transform a JSON path from API format to local directory path for sync.
* The API always returns dotted format (.flow.json, .app.json, .raw_app.json).
* This function transforms to the user's configured format (dotted or non-dotted).
* e.g., with nonDottedPaths=true: "f/my_flow.flow.json" -> "f/my_flow__flow"
* e.g., with nonDottedPaths=false: "f/my_flow.flow.json" -> "f/my_flow.flow"
*/
export function transformJsonPathToDir(
p: string,
type: FolderResourceType
): string {
// API always returns dotted format
const apiSuffix = DOTTED_SUFFIXES[type] + ".json";
if (p.endsWith(apiSuffix)) {
// Remove the API suffix and add user's configured suffix
const basePath = p.substring(0, p.length - apiSuffix.length);
return basePath + getFolderSuffixes()[type];
}
// Also handle the case where path already has user's configured format
const userSuffix = getFolderSuffixes()[type] + ".json";
if (p.endsWith(userSuffix)) {
return p.substring(0, p.length - 5); // Remove ".json"
}
// Path doesn't match expected suffix pattern, return unchanged
return p;
}