@fractary/codex 0.12.0 → 0.12.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/dist/index.js CHANGED
@@ -3,7 +3,8 @@ import * as path3 from 'path';
3
3
  import path3__default from 'path';
4
4
  import { execFile, execSync } from 'child_process';
5
5
  import { z } from 'zod';
6
- import yaml from 'js-yaml';
6
+ import * as yaml2 from 'js-yaml';
7
+ import yaml2__default from 'js-yaml';
7
8
  import * as fs3 from 'fs/promises';
8
9
  import fs3__default from 'fs/promises';
9
10
  import { promisify } from 'util';
@@ -898,12 +899,24 @@ var DirectionalSyncConfigSchema = z.object({
898
899
  /** Patterns to exclude (optional) */
899
900
  exclude: z.array(z.string()).optional()
900
901
  });
902
+ var FromCodexSyncConfigSchema = DirectionalSyncConfigSchema.refine(
903
+ (config) => {
904
+ const includeValid = config.include.every(
905
+ (pattern) => pattern.startsWith("codex://")
906
+ );
907
+ const excludeValid = !config.exclude || config.exclude.every((pattern) => pattern.startsWith("codex://"));
908
+ return includeValid && excludeValid;
909
+ },
910
+ {
911
+ message: 'from_codex patterns must use codex:// URI format (e.g., "codex://{org}/{codex_repo}/docs/**"). Plain paths like "docs/**" are not valid for from_codex.'
912
+ }
913
+ );
901
914
  var DirectionalSyncSchema = z.object({
902
915
  // New format (v0.7.0+) - Recommended
903
- // Patterns for files to push from this project to codex
916
+ // Patterns for files to push from this project to codex (plain paths)
904
917
  to_codex: DirectionalSyncConfigSchema.optional(),
905
- // Patterns for files to pull from codex to this project
906
- from_codex: DirectionalSyncConfigSchema.optional(),
918
+ // Patterns for files to pull from codex to this project (codex:// URIs required)
919
+ from_codex: FromCodexSyncConfigSchema.optional(),
907
920
  // Global exclude patterns (applied to both directions)
908
921
  exclude: z.array(z.string()).optional(),
909
922
  // Legacy format (deprecated, backward compatible)
@@ -1021,7 +1034,7 @@ function parseMetadata(content, options = {}) {
1021
1034
  const rawFrontmatter = frontmatterMatch[1];
1022
1035
  const documentContent = frontmatterMatch[2];
1023
1036
  try {
1024
- const parsed = yaml.load(rawFrontmatter);
1037
+ const parsed = yaml2__default.load(rawFrontmatter);
1025
1038
  const normalized = normalizeLegacyMetadata(parsed);
1026
1039
  const metadata = strict ? MetadataSchema.parse(normalized) : MetadataSchema.safeParse(normalized).data || {};
1027
1040
  return {
@@ -3929,17 +3942,17 @@ var SyncManager = class {
3929
3942
  if (file.operation === "create" || file.operation === "update") {
3930
3943
  const sourcePath = `${plan.source}/${file.path}`;
3931
3944
  const targetPath = `${plan.target}/${file.path}`;
3932
- const fs5 = await import('fs/promises');
3945
+ const fs6 = await import('fs/promises');
3933
3946
  const path7 = await import('path');
3934
3947
  const targetDir = path7.dirname(targetPath);
3935
- await fs5.mkdir(targetDir, { recursive: true });
3936
- await fs5.copyFile(sourcePath, targetPath);
3948
+ await fs6.mkdir(targetDir, { recursive: true });
3949
+ await fs6.copyFile(sourcePath, targetPath);
3937
3950
  synced++;
3938
3951
  } else if (file.operation === "delete") {
3939
3952
  const targetPath = `${plan.target}/${file.path}`;
3940
- const fs5 = await import('fs/promises');
3953
+ const fs6 = await import('fs/promises');
3941
3954
  try {
3942
- await fs5.unlink(targetPath);
3955
+ await fs6.unlink(targetPath);
3943
3956
  synced++;
3944
3957
  } catch (error) {
3945
3958
  if (error.code !== "ENOENT") {
@@ -4944,6 +4957,176 @@ function generateReferenceMigrationSummary(results) {
4944
4957
  return lines.join("\n");
4945
4958
  }
4946
4959
 
4947
- export { AutoSyncPatternSchema, BUILT_IN_TYPES, CODEX_URI_PREFIX, CacheManager, CachePersistence, CodexConfigSchema, CodexError, CommonRules, ConfigurationError, CustomTypeSchema, DEFAULT_CACHE_DIR, DEFAULT_FETCH_OPTIONS, DEFAULT_MIGRATION_OPTIONS, DEFAULT_PERMISSION_CONFIG, DEFAULT_SYNC_CONFIG, DEFAULT_TYPE, FilePluginFileNotFoundError, FilePluginStorage, GitHubStorage, HttpStorage, LEGACY_PATTERNS, LEGACY_REF_PREFIX, LocalStorage, MetadataSchema, PERMISSION_LEVEL_ORDER, PermissionDeniedError, PermissionManager, StorageManager, SyncManager, SyncRulesSchema, TTL, TypeRegistry, TypesConfigSchema, ValidationError, buildUri, calculateCachePath, calculateContentHash, convertLegacyReference, convertLegacyReferences, convertToUri, createCacheEntry, createCacheManager, createCachePersistence, createDefaultRegistry, createEmptyModernConfig, createEmptySyncPlan, createGitHubStorage, createHttpStorage, createLocalStorage, createPermissionManager, createRule, createRulesFromPatterns, createStorageManager, createSyncManager, createSyncPlan, deserializeCacheEntry, detectContentType, detectCurrentProject, detectVersion, estimateSyncTime, evaluatePath, evaluatePaths, evaluatePatterns, evaluatePermission, evaluatePermissions, extendType, extractOrgFromRepoName, extractRawFrontmatter, filterByPatterns, filterByPermission, filterPlanOperations, filterSyncablePaths, findLegacyReferences, formatPlanSummary, generateMigrationReport, generateReferenceMigrationSummary, getBuiltInType, getBuiltInTypeNames, getCacheEntryAge, getCacheEntryStatus, getCurrentContext, getCustomSyncDestinations, getDefaultCacheManager, getDefaultConfig, getDefaultDirectories, getDefaultPermissionManager, getDefaultRules, getDefaultStorageManager, getDirectory, getExtension, getFilename, getMigrationRequirements, getPlanStats, getRelativeCachePath, getRemainingTtl, getTargetRepos, hasContentChanged, hasFrontmatter, hasLegacyReferences, hasPermission as hasPermissionLevel, isBuiltInType, isCacheEntryFresh, isCacheEntryValid, isCurrentProjectUri, isLegacyConfig, isLegacyReference, isModernConfig, isAllowed as isPermissionAllowed, isValidUri, levelGrants, loadConfig, loadCustomTypes, matchAnyPattern, matchPattern, maxLevel, mergeFetchOptions, mergeRules, mergeTypes, migrateConfig, migrateFileReferences, minLevel, needsMigration, parseCustomDestination, parseMetadata, parseReference, parseTtl, resolveOrganization, resolveReference, resolveReferences, ruleMatchesAction, ruleMatchesContext, ruleMatchesPath, sanitizePath, serializeCacheEntry, setDefaultCacheManager, setDefaultPermissionManager, setDefaultStorageManager, shouldSyncToRepo, summarizeEvaluations, touchCacheEntry, validateCustomTypes, validateMetadata, validateMigratedConfig, validateOrg, validatePath, validateRules2 as validatePermissionRules, validateProject, validateRules, validateUri };
4960
+ // src/core/env/index.ts
4961
+ function expandEnvVars(value, options = {}) {
4962
+ const env = options.env ?? process.env;
4963
+ return value.replace(/\$\{([^}]+)\}/g, (match, varName) => {
4964
+ const envValue = env[varName];
4965
+ if (envValue === void 0) {
4966
+ if (options.warnOnMissing) {
4967
+ console.warn(`Warning: Environment variable ${varName} is not set`);
4968
+ }
4969
+ if (options.onMissing) {
4970
+ options.onMissing(varName);
4971
+ }
4972
+ return match;
4973
+ }
4974
+ return envValue;
4975
+ });
4976
+ }
4977
+ function expandEnvVarsInConfig(config, options = {}) {
4978
+ if (typeof config === "string") {
4979
+ return expandEnvVars(config, options);
4980
+ }
4981
+ if (Array.isArray(config)) {
4982
+ return config.map((item) => expandEnvVarsInConfig(item, options));
4983
+ }
4984
+ if (config !== null && typeof config === "object") {
4985
+ const result = {};
4986
+ for (const [key, value] of Object.entries(config)) {
4987
+ result[key] = expandEnvVarsInConfig(value, options);
4988
+ }
4989
+ return result;
4990
+ }
4991
+ return config;
4992
+ }
4993
+ function hasEnvVars(value) {
4994
+ return /\$\{[^}]+\}/.test(value);
4995
+ }
4996
+ function extractEnvVarNames(value) {
4997
+ const matches = value.matchAll(/\$\{([^}]+)\}/g);
4998
+ const names = [];
4999
+ for (const match of matches) {
5000
+ if (match[1]) {
5001
+ names.push(match[1]);
5002
+ }
5003
+ }
5004
+ return names;
5005
+ }
5006
+ async function readCodexConfig(configPath, options = {}) {
5007
+ const content = await fs3.readFile(configPath, "utf-8");
5008
+ const rawConfig = yaml2.load(content);
5009
+ let config;
5010
+ if (rawConfig?.codex && typeof rawConfig.codex === "object") {
5011
+ config = rawConfig.codex;
5012
+ } else {
5013
+ config = rawConfig;
5014
+ }
5015
+ if (!config.organization) {
5016
+ throw new Error("Invalid config: organization is required");
5017
+ }
5018
+ if (options.expandEnv !== false) {
5019
+ const envOptions = {
5020
+ env: options.env,
5021
+ warnOnMissing: options.warnOnMissingEnv
5022
+ };
5023
+ config = expandEnvVarsInConfig(config, envOptions);
5024
+ }
5025
+ return config;
5026
+ }
5027
+ async function readUnifiedConfig(configPath, options = {}) {
5028
+ const content = await fs3.readFile(configPath, "utf-8");
5029
+ let config = yaml2.load(content);
5030
+ if (options.expandEnv !== false) {
5031
+ const envOptions = {
5032
+ env: options.env,
5033
+ warnOnMissing: options.warnOnMissingEnv
5034
+ };
5035
+ config = expandEnvVarsInConfig(config, envOptions);
5036
+ }
5037
+ return config;
5038
+ }
5039
+ function isUnifiedConfig(config) {
5040
+ if (config === null || typeof config !== "object") {
5041
+ return false;
5042
+ }
5043
+ const maybeUnified = config;
5044
+ return "codex" in maybeUnified && maybeUnified.codex !== null && typeof maybeUnified.codex === "object";
5045
+ }
5046
+
5047
+ // src/core/utils/index.ts
5048
+ var DURATION_MULTIPLIERS = {
5049
+ s: 1,
5050
+ // seconds
5051
+ m: 60,
5052
+ // minutes
5053
+ h: 3600,
5054
+ // hours
5055
+ d: 86400,
5056
+ // days
5057
+ w: 604800,
5058
+ // weeks (7 days)
5059
+ M: 2592e3,
5060
+ // months (30 days)
5061
+ y: 31536e3
5062
+ // years (365 days)
5063
+ };
5064
+ var SIZE_MULTIPLIERS = {
5065
+ B: 1,
5066
+ KB: 1024,
5067
+ MB: 1024 * 1024,
5068
+ GB: 1024 * 1024 * 1024,
5069
+ TB: 1024 * 1024 * 1024 * 1024
5070
+ };
5071
+ function parseDuration(duration) {
5072
+ if (typeof duration === "number") {
5073
+ return duration;
5074
+ }
5075
+ const match = duration.match(/^(\d+(?:\.\d+)?)\s*([smhdwMy])$/);
5076
+ if (!match || !match[1] || !match[2]) {
5077
+ throw new Error(`Invalid duration format: ${duration}. Use format like "1h", "7d", "1M"`);
5078
+ }
5079
+ const valueStr = match[1];
5080
+ const unit = match[2];
5081
+ const value = parseFloat(valueStr);
5082
+ const multiplier = DURATION_MULTIPLIERS[unit];
5083
+ if (multiplier === void 0) {
5084
+ throw new Error(`Unknown duration unit: ${unit}`);
5085
+ }
5086
+ return Math.round(value * multiplier);
5087
+ }
5088
+ function parseSize(size) {
5089
+ if (typeof size === "number") {
5090
+ return size;
5091
+ }
5092
+ const match = size.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)$/i);
5093
+ if (!match || !match[1] || !match[2]) {
5094
+ throw new Error(`Invalid size format: ${size}. Use format like "100MB", "1GB"`);
5095
+ }
5096
+ const valueStr = match[1];
5097
+ const unit = match[2];
5098
+ const value = parseFloat(valueStr);
5099
+ const multiplier = SIZE_MULTIPLIERS[unit.toUpperCase()];
5100
+ if (multiplier === void 0) {
5101
+ throw new Error(`Unknown size unit: ${unit}`);
5102
+ }
5103
+ return Math.round(value * multiplier);
5104
+ }
5105
+ function formatBytes2(bytes) {
5106
+ if (bytes < 1024) return `${bytes} B`;
5107
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
5108
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
5109
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
5110
+ }
5111
+ function formatDuration(ms) {
5112
+ if (ms < 1e3) return `${ms}ms`;
5113
+ if (ms < 6e4) return `${(ms / 1e3).toFixed(1)}s`;
5114
+ if (ms < 36e5) return `${(ms / 6e4).toFixed(1)}m`;
5115
+ return `${(ms / 36e5).toFixed(1)}h`;
5116
+ }
5117
+ function formatSeconds(seconds) {
5118
+ if (seconds < 60) return `${seconds}s`;
5119
+ if (seconds < 3600) return `${(seconds / 60).toFixed(1)}m`;
5120
+ if (seconds < 86400) return `${(seconds / 3600).toFixed(1)}h`;
5121
+ return `${(seconds / 86400).toFixed(1)}d`;
5122
+ }
5123
+ function isValidDuration(value) {
5124
+ return /^\d+(?:\.\d+)?\s*[smhdwMy]$/.test(value);
5125
+ }
5126
+ function isValidSize(value) {
5127
+ return /^\d+(?:\.\d+)?\s*(B|KB|MB|GB|TB)$/i.test(value);
5128
+ }
5129
+
5130
+ export { AutoSyncPatternSchema, BUILT_IN_TYPES, CODEX_URI_PREFIX, CacheManager, CachePersistence, CodexConfigSchema, CodexError, CommonRules, ConfigurationError, CustomTypeSchema, DEFAULT_CACHE_DIR, DEFAULT_FETCH_OPTIONS, DEFAULT_MIGRATION_OPTIONS, DEFAULT_PERMISSION_CONFIG, DEFAULT_SYNC_CONFIG, DEFAULT_TYPE, FilePluginFileNotFoundError, FilePluginStorage, GitHubStorage, HttpStorage, LEGACY_PATTERNS, LEGACY_REF_PREFIX, LocalStorage, MetadataSchema, PERMISSION_LEVEL_ORDER, PermissionDeniedError, PermissionManager, StorageManager, SyncManager, SyncRulesSchema, TTL, TypeRegistry, TypesConfigSchema, ValidationError, buildUri, calculateCachePath, calculateContentHash, convertLegacyReference, convertLegacyReferences, convertToUri, createCacheEntry, createCacheManager, createCachePersistence, createDefaultRegistry, createEmptyModernConfig, createEmptySyncPlan, createGitHubStorage, createHttpStorage, createLocalStorage, createPermissionManager, createRule, createRulesFromPatterns, createStorageManager, createSyncManager, createSyncPlan, deserializeCacheEntry, detectContentType, detectCurrentProject, detectVersion, estimateSyncTime, evaluatePath, evaluatePaths, evaluatePatterns, evaluatePermission, evaluatePermissions, expandEnvVars, expandEnvVarsInConfig, extendType, extractEnvVarNames, extractOrgFromRepoName, extractRawFrontmatter, filterByPatterns, filterByPermission, filterPlanOperations, filterSyncablePaths, findLegacyReferences, formatBytes2 as formatBytes, formatDuration, formatPlanSummary, formatSeconds, generateMigrationReport, generateReferenceMigrationSummary, getBuiltInType, getBuiltInTypeNames, getCacheEntryAge, getCacheEntryStatus, getCurrentContext, getCustomSyncDestinations, getDefaultCacheManager, getDefaultConfig, getDefaultDirectories, getDefaultPermissionManager, getDefaultRules, getDefaultStorageManager, getDirectory, getExtension, getFilename, getMigrationRequirements, getPlanStats, getRelativeCachePath, getRemainingTtl, getTargetRepos, hasContentChanged, hasEnvVars, hasFrontmatter, hasLegacyReferences, hasPermission as hasPermissionLevel, isBuiltInType, isCacheEntryFresh, isCacheEntryValid, isCurrentProjectUri, isLegacyConfig, isLegacyReference, isModernConfig, isAllowed as isPermissionAllowed, isUnifiedConfig, isValidDuration, isValidSize, isValidUri, levelGrants, loadConfig, loadCustomTypes, matchAnyPattern, matchPattern, maxLevel, mergeFetchOptions, mergeRules, mergeTypes, migrateConfig, migrateFileReferences, minLevel, needsMigration, parseCustomDestination, parseDuration, parseMetadata, parseReference, parseSize, parseTtl, readCodexConfig, readUnifiedConfig, resolveOrganization, resolveReference, resolveReferences, ruleMatchesAction, ruleMatchesContext, ruleMatchesPath, sanitizePath, serializeCacheEntry, setDefaultCacheManager, setDefaultPermissionManager, setDefaultStorageManager, shouldSyncToRepo, summarizeEvaluations, touchCacheEntry, validateCustomTypes, validateMetadata, validateMigratedConfig, validateOrg, validatePath, validateRules2 as validatePermissionRules, validateProject, validateRules, validateUri };
4948
5131
  //# sourceMappingURL=index.js.map
4949
5132
  //# sourceMappingURL=index.js.map