guessit-js 4.5.4 → 4.7.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/README.md CHANGED
@@ -27,7 +27,9 @@ npm install guessit-js
27
27
 
28
28
  ## CLI
29
29
 
30
- Mirrors the Python `guessit` command:
30
+ **Drop-in replacement** for the Python `guessit` command — same flags, same
31
+ output formats (verified against the real Python CLI in CI). Installs both
32
+ `guessit-js` and `guessit` binaries:
31
33
 
32
34
  ```bash
33
35
  npx guessit-js "The.Dark.Knight.2008.1080p.BluRay.x264-GROUP.mkv"
@@ -47,7 +49,17 @@ npx guessit-js -p # list detectable properties
47
49
  Parsing options match the Python CLI: `-n` name-only, `-Y`/`-D` date order,
48
50
  `-L`/`-C` allowed languages/countries, `-E` episode-prefer-number,
49
51
  `-T`/`-G` expected title/group, `--includes`/`--excludes`, `-s` single-value,
50
- `-c` JSON config file. See `npx guessit-js --help`.
52
+ `-v` verbose. User config is auto-loaded from `~/.guessit/options.json` and
53
+ `~/.config/guessit/options.json` (`.yaml`/`.yml` too; disable with
54
+ `--no-user-config`), plus explicit `-c <file>`. See `npx guessit-js --help`.
55
+
56
+ Extras beyond the Python CLI:
57
+
58
+ ```bash
59
+ npx guessit-js --serve 3847 # instant REST API (see below)
60
+ npx guessit-js --benchmark 1000 "Movie.2020.1080p.mkv" # throughput report
61
+ eval "$(npx guessit-js --completion bash)" # shell completion (bash/zsh)
62
+ ```
51
63
 
52
64
  ## Usage
53
65
 
@@ -131,11 +143,20 @@ Regenerate the schema (after parsing changes) with `npm run schema`. A test (`te
131
143
 
132
144
  ## REST API
133
145
 
146
+ No install needed beyond the package itself:
147
+
134
148
  ```bash
135
- npm start # port 3847
149
+ npx guessit-js --serve # port 3847 (or --serve 8080 / PORT env)
136
150
  curl "http://localhost:3847/api/guessit?filename=Movie.2024.1080p.mkv"
151
+ curl -X POST http://localhost:3847/api/guessit \
152
+ -H 'Content-Type: application/json' \
153
+ -d '{"filenames": ["A.2020.mkv", "B.S01E02.mkv"], "options": {"type": "episode"}}'
137
154
  ```
138
155
 
156
+ CLI parsing flags become server defaults: `guessit-js --serve -t episode -L en`.
157
+ The repo also ships a fuller dev server (`npm start`) with the demo page,
158
+ Swagger UI at `/docs`, and static WASM serving.
159
+
139
160
  ## WASM
140
161
 
141
162
  For non-JS environments (Rust, Go, C++, edge compute). Uses [Javy](https://github.com/bytecodealliance/javy) (QuickJS → WASM).
package/bin/cli.mjs CHANGED
@@ -1,47 +1,78 @@
1
1
  #!/usr/bin/env node
2
- // guessit-js CLI — mirrors the Python `guessit` command-line interface.
2
+ // guessit-js CLI — drop-in replacement for the Python `guessit` command.
3
+ // Same flags, same output formats (For:/GuessIt found:, -j compact JSON with
4
+ // Python separators, -y ?-key YAML), same user-config loading.
3
5
  // Zero dependencies; the library is bundled in dist/.
4
- import { readFileSync } from 'fs';
6
+ import { readFileSync, existsSync } from 'fs';
7
+ import { homedir } from 'os';
8
+ import { join } from 'path';
5
9
  import { guessit, properties as apiProperties, version } from '../dist/guessit-js.js';
6
10
 
7
- const HELP = `guessit-js ${version} — extract metadata from media filenames
11
+ // Python's GuessitEncoder emits babelfish `.name` in JSON ("English",
12
+ // "UNITED STATES") while YAML uses str() ("en", "pt-BR", "US"). Mirror both.
13
+ const ALPHA3_TO_2 = {"eng":"en","fra":"fr","deu":"de","spa":"es","ita":"it","por":"pt","rus":"ru","jpn":"ja","zho":"zh","kor":"ko","ara":"ar","hin":"hi","tur":"tr","pol":"pl","nld":"nl","swe":"sv","dan":"da","nor":"no","fin":"fi","hun":"hu","ces":"cs","ron":"ro","ukr":"uk","heb":"he","cat":"ca","vie":"vi","tha":"th","ind":"id","mal":"ml","tel":"te","tam":"ta","bul":"bg","hrv":"hr","srp":"sr","slk":"sk","slv":"sl","ell":"el","lit":"lt","lav":"lv","est":"et","glg":"gl","eus":"eu","ben":"bn","isl":"is","mkd":"mk","bos":"bs","alb":"sq","per":"fa","msa":"ms","mon":"mn","urd":"ur","pan":"pa","guj":"gu","kan":"kn","mar":"mr","asm":"as","mya":"my","khm":"km","lao":"lo"};
14
+ const LANGUAGE_NAMES = {"eng":"English","fra":"French","deu":"German","spa":"Spanish","ita":"Italian","por":"Portuguese","rus":"Russian","jpn":"Japanese","zho":"Chinese","kor":"Korean","ara":"Arabic","hin":"Hindi","tur":"Turkish","pol":"Polish","nld":"Dutch","swe":"Swedish","dan":"Danish","nor":"Norwegian","fin":"Finnish","hun":"Hungarian","ces":"Czech","ron":"Romanian","ukr":"Ukrainian","heb":"Hebrew","cat":"Catalan","vie":"Vietnamese","tha":"Thai","ind":"Indonesian","mal":"Malayalam","tel":"Telugu","tam":"Tamil","bul":"Bulgarian","hrv":"Croatian","srp":"Serbian","slk":"Slovak","slv":"Slovenian","ell":"Greek","lit":"Lithuanian","lav":"Latvian","est":"Estonian","glg":"Galician","eus":"Basque","ben":"Bengali","isl":"Icelandic","mkd":"Macedonian","bos":"Bosnian","alb":"Albanian","per":"Persian","msa":"Malay","mon":"Mongolian","urd":"Urdu","pan":"Punjabi","guj":"Gujarati","kan":"Kannada","mar":"Marathi","asm":"Assamese","mya":"Burmese","khm":"Khmer","lao":"Lao"};
15
+ const COUNTRY_NAMES = {"US":"UNITED STATES","GB":"UNITED KINGDOM","AU":"AUSTRALIA","CA":"CANADA","NZ":"NEW ZEALAND","IE":"IRELAND","FR":"FRANCE","DE":"GERMANY","ES":"SPAIN","IT":"ITALY","BR":"BRAZIL","PT":"PORTUGAL","RU":"RUSSIAN FEDERATION","JP":"JAPAN","CN":"CHINA","TW":"TAIWAN, PROVINCE OF CHINA","HK":"HONG KONG","KR":"KOREA, REPUBLIC OF","IN":"INDIA","MX":"MEXICO","NL":"NETHERLANDS","SE":"SWEDEN","NO":"NORWAY","DK":"DENMARK","FI":"FINLAND","PL":"POLAND","CH":"SWITZERLAND","AT":"AUSTRIA","BE":"BELGIUM","CZ":"CZECHIA","GR":"GREECE","HU":"HUNGARY","RO":"ROMANIA","TR":"TURKEY","UA":"UKRAINE","AR":"ARGENTINA","ZA":"SOUTH AFRICA"};
8
16
 
9
- Usage: guessit-js [options] <filename> [<filename> ...]
10
- guessit-js [options] @list.txt filenames from file (one per line)
11
- guessit-js [options] -f list.txt same as @list.txt (use - for stdin)
12
- echo "Movie.mkv" | guessit-js [options] filenames from piped stdin
17
+ const HELP = `usage: guessit-js [options] [filename ...]
18
+
19
+ positional arguments:
20
+ filename Filename or release name to guess (@list.txt reads
21
+ one filename per line; - reads stdin)
22
+
23
+ Naming:
24
+ -t TYPE, --type TYPE The suggested file type: movie or episode
25
+ -n, --name-only Parse files as name only, without extension
26
+ -Y, --date-year-first Take the year first when parsing an ambiguous date
27
+ -D, --date-day-first Take the day first when parsing an ambiguous date
28
+ -L ALLOWED_LANGUAGES, --allowed-languages ALLOWED_LANGUAGES
29
+ Allowed language (comma-separated, repeatable)
30
+ -C ALLOWED_COUNTRIES, --allowed-countries ALLOWED_COUNTRIES
31
+ Allowed country (comma-separated, repeatable)
32
+ -E, --episode-prefer-number
33
+ Guess "serie.213.avi" as episode 213
34
+ -T EXPECTED_TITLE, --expected-title EXPECTED_TITLE
35
+ Expected title (repeatable)
36
+ -G EXPECTED_GROUP, --expected-group EXPECTED_GROUP
37
+ Expected release group (repeatable)
38
+ --includes INCLUDES Properties to include (comma-separated, repeatable)
39
+ --excludes EXCLUDES Properties to exclude (comma-separated, repeatable)
40
+
41
+ Input:
42
+ -f INPUT_FILE, --input-file INPUT_FILE
43
+ Read filenames from this file (- for stdin)
13
44
 
14
45
  Output:
15
- -j, --json JSON (single object, or array for multiple inputs)
16
- --jsonl one JSON object per line (streaming-friendly)
17
- -y, --yaml YAML
18
- -P, --show-property <name> print only this property's value
19
- -i, --output-input-string include the input string in the result
20
-
21
- Parsing options:
22
- -t, --type <type> suggested type: movie or episode
23
- -n, --name-only parse as a name without extension
24
- -Y, --date-year-first ambiguous dates: year first
25
- -D, --date-day-first ambiguous dates: day first
26
- -L, --allowed-languages comma-separated language codes (e.g. en,fr)
27
- -C, --allowed-countries comma-separated country codes (e.g. us,gb)
28
- -E, --episode-prefer-number prefer episode over season for lone numbers
29
- -T, --expected-title expected title (repeatable)
30
- -G, --expected-group expected release group (repeatable)
31
- --includes <props> comma-separated properties to include (repeatable)
32
- --excludes <props> comma-separated properties to exclude (repeatable)
33
- -s, --single-value only the first value per property
34
- -a, --advanced raw match data (start/end/raw per property)
35
- -c, --config <file> JSON file with extra options (merged in)
36
-
37
- Introspection:
38
- -p, --properties list all detectable property names
39
- -V, --values list all property names with their possible values
40
-
41
- Misc:
42
- -v, --version print version
43
- -h, --help this help
44
- -- end of options; everything after is a filename
46
+ -v, --verbose Display debug output
47
+ -P SHOW_PROPERTY, --show-property SHOW_PROPERTY
48
+ Display only the given property value
49
+ -a, --advanced Display advanced information for filename guesses
50
+ -s, --single-value Keep only the first value found for each property
51
+ -j, --json Display information for filename guesses as json output
52
+ --jsonl Alias of --json (one object per line)
53
+ -y, --yaml Display information for filename guesses as yaml output
54
+ -i, --output-input-string
55
+ Add input_string property in the output
56
+
57
+ Configuration:
58
+ -c CONFIG_FILE, --config CONFIG_FILE
59
+ Config file to use (JSON, or simple flat YAML)
60
+ --no-user-config Disable user config (~/.guessit/options.json,
61
+ ~/.config/guessit/options.json, .yaml/.yml variants)
62
+ --no-default-config Disable the embedded default config
63
+
64
+ Information:
65
+ -p, --properties Display properties that can be guessed
66
+ -V, --values Display property values that can be guessed
67
+ --version Display the guessit-js version banner
68
+
69
+ Extras (not in the Python CLI):
70
+ --serve [PORT] Start a REST API server (default port 3847;
71
+ GET /api/guessit?filename=..., POST {filename|filenames})
72
+ --benchmark [N] Parse the given filenames N times (default 1000)
73
+ and report throughput
74
+ --completion SHELL Print a bash or zsh completion script
75
+ (eval "$(guessit-js --completion bash)")
45
76
 
46
77
  Exit codes: 0 success, 1 processing error, 2 usage error.`;
47
78
 
@@ -55,22 +86,62 @@ function readLines(path) {
55
86
  return text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
56
87
  }
57
88
 
89
+ // Minimal config-file reader: JSON first, then a flat "key: value" YAML subset
90
+ // (scalars, [a, b] inline lists, "- item" block lists).
91
+ function readConfigFile(path) {
92
+ const text = readFileSync(path, 'utf8');
93
+ try { return JSON.parse(text); } catch { /* fall through to flat YAML */ }
94
+ const out = {};
95
+ let listKey = null;
96
+ for (const rawLine of text.split(/\r?\n/)) {
97
+ const line = rawLine.replace(/#.*$/, '').trimEnd();
98
+ if (!line.trim()) continue;
99
+ const item = line.match(/^\s+-\s+(.*)$/);
100
+ if (item && listKey) { out[listKey].push(parseScalar(item[1])); continue; }
101
+ const kv = line.match(/^([\w-]+):\s*(.*)$/);
102
+ if (!kv) continue;
103
+ const [, key, value] = kv;
104
+ if (!value) { out[key] = []; listKey = key; continue; }
105
+ listKey = null;
106
+ if (value.startsWith('[') && value.endsWith(']')) {
107
+ out[key] = value.slice(1, -1).split(',').map((s) => parseScalar(s.trim())).filter((s) => s !== '');
108
+ } else {
109
+ out[key] = parseScalar(value);
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+ function parseScalar(s) {
115
+ if (s === 'true' || s === 'yes') return true;
116
+ if (s === 'false' || s === 'no') return false;
117
+ if (s === 'null' || s === '~') return null;
118
+ if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
119
+ return s.replace(/^['"]|['"]$/g, '');
120
+ }
121
+
58
122
  // ---- argument parsing -------------------------------------------------------
59
123
  const args = process.argv.slice(2);
60
124
  const filenames = [];
61
- const options = {};
62
- let output = 'lines';
125
+ const cliOptions = {};
126
+ const configOptions = {};
127
+ let output = 'default';
63
128
  let showProperty = null;
129
+ let verbose = false;
64
130
  let listProperties = false;
65
131
  let listValues = false;
132
+ let noUserConfig = false;
66
133
  let endOfOptions = false;
134
+ let serve = false;
135
+ let servePort = 3847;
136
+ let benchmark = 0;
137
+ let completionShell = null;
67
138
 
68
139
  const needsValue = (a, i) => {
69
140
  if (i + 1 >= args.length) fail(`option ${a} requires a value`);
70
141
  return args[i + 1];
71
142
  };
72
143
  const pushList = (key, raw) => {
73
- options[key] = (options[key] || []).concat(raw.split(',').map((s) => s.trim()).filter(Boolean));
144
+ cliOptions[key] = (cliOptions[key] || []).concat(raw.split(',').map((s) => s.trim()).filter(Boolean));
74
145
  };
75
146
 
76
147
  for (let i = 0; i < args.length; i++) {
@@ -83,45 +154,139 @@ for (let i = 0; i < args.length; i++) {
83
154
  }
84
155
  switch (a) {
85
156
  case '--': endOfOptions = true; break;
86
- case '-j': case '--json': output = 'json'; break;
87
- case '--jsonl': output = 'jsonl'; break;
157
+ case '-j': case '--json': case '--jsonl': output = 'json'; break;
88
158
  case '-y': case '--yaml': output = 'yaml'; break;
89
159
  case '-P': case '--show-property': showProperty = needsValue(a, i); i++; break;
90
160
  case '-f': case '--input-file': filenames.push(...readLines(needsValue(a, i))); i++; break;
91
- case '-i': case '--output-input-string': options.output_input_string = true; break;
92
- case '-t': case '--type': options.type = needsValue(a, i); i++; break;
93
- case '-n': case '--name-only': options.name_only = true; break;
94
- case '-Y': case '--date-year-first': options.date_year_first = true; break;
95
- case '-D': case '--date-day-first': options.date_day_first = true; break;
161
+ case '-i': case '--output-input-string': cliOptions.output_input_string = true; break;
162
+ case '-t': case '--type': cliOptions.type = needsValue(a, i); i++; break;
163
+ case '-n': case '--name-only': cliOptions.name_only = true; break;
164
+ case '-Y': case '--date-year-first': cliOptions.date_year_first = true; break;
165
+ case '-D': case '--date-day-first': cliOptions.date_day_first = true; break;
96
166
  case '-L': case '--allowed-languages': pushList('allowed_languages', needsValue(a, i)); i++; break;
97
167
  case '-C': case '--allowed-countries': pushList('allowed_countries', needsValue(a, i)); i++; break;
98
- case '-E': case '--episode-prefer-number': options.episode_prefer_number = true; break;
168
+ case '-E': case '--episode-prefer-number': cliOptions.episode_prefer_number = true; break;
99
169
  case '-T': case '--expected-title': pushList('expected_title', needsValue(a, i)); i++; break;
100
170
  case '-G': case '--expected-group': pushList('expected_group', needsValue(a, i)); i++; break;
101
171
  case '--includes': pushList('includes', needsValue(a, i)); i++; break;
102
172
  case '--excludes': pushList('excludes', needsValue(a, i)); i++; break;
103
- case '-s': case '--single-value': options.single_value = true; break;
104
- case '-a': case '--advanced': options.advanced = true; break;
173
+ case '-s': case '--single-value': cliOptions.single_value = true; break;
174
+ case '-a': case '--advanced': cliOptions.advanced = true; break;
175
+ case '-v': case '--verbose': verbose = true; break;
105
176
  case '-c': case '--config': {
106
177
  const path = needsValue(a, i); i++;
107
- try { Object.assign(options, JSON.parse(readFileSync(path, 'utf8'))); }
178
+ try { Object.assign(configOptions, readConfigFile(path)); }
108
179
  catch (e) { fail(`cannot read config ${path}: ${e.message}`); }
109
180
  break;
110
181
  }
182
+ case '--no-user-config': noUserConfig = true; cliOptions.no_user_config = true; break;
183
+ case '--no-default-config': cliOptions.no_default_config = true; break;
111
184
  case '-p': case '--properties': listProperties = true; break;
112
185
  case '-V': case '--values': listValues = true; break;
113
- case '-v': case '--version': console.log(version); process.exit(0); break;
186
+ case '--serve':
187
+ serve = true;
188
+ if (args[i + 1] && /^\d+$/.test(args[i + 1])) { servePort = Number(args[++i]); }
189
+ else if (process.env.PORT) servePort = Number(process.env.PORT);
190
+ break;
191
+ case '--benchmark':
192
+ benchmark = args[i + 1] && /^\d+$/.test(args[i + 1]) ? Number(args[++i]) : 1000;
193
+ break;
194
+ case '--completion': completionShell = needsValue(a, i); i++; break;
195
+ case '--version': {
196
+ console.log('+-------------------------------------------------------+');
197
+ console.log(`+ GuessIt-JS ${version}`.padEnd(56) + '+');
198
+ console.log('+-------------------------------------------------------+');
199
+ console.log('| Please report any bug or feature request at |');
200
+ console.log('| https://github.com/opensubtitles/guessit-js/issues. |');
201
+ console.log('+-------------------------------------------------------+');
202
+ process.exit(0);
203
+ break;
204
+ }
114
205
  case '-h': case '--help': console.log(HELP); process.exit(0); break;
115
206
  default: fail(`unknown option: ${a} — see --help`);
116
207
  }
117
208
  }
118
209
 
210
+ // User config, same locations as Python guessit.
211
+ if (!noUserConfig) {
212
+ const home = homedir();
213
+ for (const dir of [join(home, '.guessit'), join(home, '.config', 'guessit')]) {
214
+ for (const ext of ['json', 'yaml', 'yml']) {
215
+ const path = join(dir, `options.${ext}`);
216
+ if (existsSync(path)) {
217
+ try { Object.assign(configOptions, readConfigFile(path)); } catch { /* ignore broken user config */ }
218
+ }
219
+ }
220
+ }
221
+ }
222
+
223
+ // Precedence: user/explicit config < CLI flags.
224
+ const options = { ...configOptions, ...cliOptions };
225
+ for (const key of ['allowed_languages', 'allowed_countries', 'expected_title', 'expected_group', 'includes', 'excludes']) {
226
+ if (configOptions[key] && cliOptions[key]) options[key] = [...configOptions[key], ...cliOptions[key]];
227
+ }
228
+
119
229
  if (options.type && options.type !== 'movie' && options.type !== 'episode') {
120
230
  fail(`invalid --type "${options.type}": must be movie or episode`);
121
231
  }
122
232
 
123
- // ---- output helpers ---------------------------------------------------------
124
- function toYaml(value, indent = '') {
233
+ // ---- value + output formatting ---------------------------------------------
234
+ // Python: JSON output uses babelfish .name ("English", "UNITED STATES"),
235
+ // YAML output uses str() ("en", "pt-BR", "US"); dates become ISO strings.
236
+ function display(v, mode, key) {
237
+ if (Array.isArray(v)) return v.map((x) => display(x, mode, key));
238
+ if (v instanceof Date) return v.toISOString().slice(0, 10);
239
+ if (v && typeof v === 'object') {
240
+ if (typeof v.alpha3 === 'string') {
241
+ if (mode === 'yaml') {
242
+ const base = ALPHA3_TO_2[v.alpha3] || v.alpha3;
243
+ return v.country ? `${base}-${v.country}` : base;
244
+ }
245
+ return LANGUAGE_NAMES[v.alpha3] || v.alpha3;
246
+ }
247
+ const out = {};
248
+ for (const [k, val] of Object.entries(v)) out[k] = display(val, mode, k);
249
+ return out;
250
+ }
251
+ if (key === 'country' && typeof v === 'string' && mode !== 'yaml') {
252
+ return COUNTRY_NAMES[v] || v;
253
+ }
254
+ return v;
255
+ }
256
+
257
+ // json.dumps-compatible emitters (Python uses ", " / ": " separators).
258
+ function pyJson(v) {
259
+ if (Array.isArray(v)) return '[' + v.map(pyJson).join(', ') + ']';
260
+ if (v && typeof v === 'object') {
261
+ return '{' + Object.entries(v).map(([k, val]) => `${JSON.stringify(k)}: ${pyJson(val)}`).join(', ') + '}';
262
+ }
263
+ return JSON.stringify(v);
264
+ }
265
+ function pyJsonIndent(v, level = 1) {
266
+ const pad = ' '.repeat(level);
267
+ const close = ' '.repeat(level - 1);
268
+ if (Array.isArray(v)) {
269
+ if (!v.length) return '[]';
270
+ return '[\n' + v.map((x) => pad + pyJsonIndent(x, level + 1)).join(',\n') + `\n${close}]`;
271
+ }
272
+ if (v && typeof v === 'object') {
273
+ const entries = Object.entries(v);
274
+ if (!entries.length) return '{}';
275
+ return '{\n' + entries.map(([k, x]) => `${pad}${JSON.stringify(k)}: ${pyJsonIndent(x, level + 1)}`).join(',\n') + `\n${close}}`;
276
+ }
277
+ return JSON.stringify(v);
278
+ }
279
+
280
+ function yamlScalar(v) {
281
+ if (typeof v !== 'string') return String(v);
282
+ const needsQuote =
283
+ /^[\s'"&*?|>%@`!,\[\]{}#-]/.test(v) || /: /.test(v) || / #/.test(v) ||
284
+ /[\n\t]/.test(v) || /\s$/.test(v) || v.endsWith(':') ||
285
+ /^(true|false|null|yes|no|on|off|~)$/i.test(v) || /^-?[\d.]+$/.test(v);
286
+ // pyyaml prefers single-quoted style
287
+ return needsQuote ? `'${v.replace(/'/g, "''")}'` : v;
288
+ }
289
+ function toYaml(value, indent) {
125
290
  if (Array.isArray(value)) {
126
291
  return value.map((v) =>
127
292
  typeof v === 'object' && v !== null
@@ -130,26 +295,26 @@ function toYaml(value, indent = '') {
130
295
  ).join('\n');
131
296
  }
132
297
  if (typeof value === 'object' && value !== null) {
133
- return Object.entries(value).map(([k, v]) =>
134
- typeof v === 'object' && v !== null
135
- ? `${indent}${k}:\n${toYaml(v, indent + ' ')}`
136
- : `${indent}${k}: ${yamlScalar(v)}`
137
- ).join('\n');
298
+ return Object.entries(value).map(([k, v]) => {
299
+ if (Array.isArray(v)) return `${indent}${k}:\n${toYaml(v, indent)}`; // pyyaml: list items at key level
300
+ if (typeof v === 'object' && v !== null) return `${indent}${k}:\n${toYaml(v, indent + ' ')}`;
301
+ return `${indent}${k}: ${yamlScalar(v)}`;
302
+ }).join('\n');
138
303
  }
139
304
  return indent + yamlScalar(value);
140
305
  }
141
- function yamlScalar(v) {
142
- if (typeof v !== 'string') return String(v);
143
- return /^[\w][\w .+-]*$/.test(v) && !/^(true|false|null|yes|no|on|off|[\d.]+)$/i.test(v)
144
- ? v
145
- : JSON.stringify(v);
146
- }
147
306
 
148
- function printLines(name, result, many) {
149
- if (many) console.log(`For: ${name}`);
150
- for (const [k, v] of Object.entries(result)) {
151
- console.log(`${many ? ' ' : ''}${k}: ${typeof v === 'object' && v !== null ? JSON.stringify(v) : v}`);
307
+ // Advanced mode returns live Match objects; reduce them to the Python shape.
308
+ function simplifyAdvanced(v) {
309
+ if (Array.isArray(v)) return v.map(simplifyAdvanced);
310
+ if (v && typeof v === 'object' && 'start' in v && 'end' in v) {
311
+ const out = { value: display(v.value, 'json') };
312
+ if (v.raw) out.raw = v.raw; // Python omits raw for synthesized matches
313
+ out.start = v.start;
314
+ out.end = v.end;
315
+ return out;
152
316
  }
317
+ return v;
153
318
  }
154
319
 
155
320
  // ---- introspection modes ----------------------------------------------------
@@ -166,55 +331,160 @@ if (listProperties || listValues) {
166
331
  process.exit(0);
167
332
  }
168
333
 
334
+ // ---- shell completion -------------------------------------------------------
335
+ if (completionShell) {
336
+ const flags = '-t --type -n --name-only -Y --date-year-first -D --date-day-first -L --allowed-languages -C --allowed-countries -E --episode-prefer-number -T --expected-title -G --expected-group --includes --excludes -f --input-file -v --verbose -P --show-property -a --advanced -s --single-value -j --json --jsonl -y --yaml -i --output-input-string -c --config --no-user-config --no-default-config -p --properties -V --values --version --serve --benchmark --completion -h --help';
337
+ if (completionShell === 'bash') {
338
+ console.log(`_guessit_js() {
339
+ local cur="\${COMP_WORDS[COMP_CWORD]}"
340
+ if [[ "$cur" == -* ]]; then
341
+ COMPREPLY=( $(compgen -W "${flags}" -- "$cur") )
342
+ else
343
+ COMPREPLY=( $(compgen -f -- "$cur") )
344
+ fi
345
+ }
346
+ complete -F _guessit_js guessit-js guessit`);
347
+ } else if (completionShell === 'zsh') {
348
+ console.log(`#compdef guessit-js guessit
349
+ _arguments '*: :{ _alternative "flags:flag:(${flags})" "files:filename:_files" }'`);
350
+ } else {
351
+ fail(`unsupported shell "${completionShell}": use bash or zsh`);
352
+ }
353
+ process.exit(0);
354
+ }
355
+
356
+ // ---- REST API server --------------------------------------------------------
357
+ if (serve) {
358
+ const { createServer } = await import('http');
359
+ const baseOptions = options;
360
+ const sendJson = (res, status, data) => {
361
+ res.writeHead(status, {
362
+ 'Content-Type': 'application/json; charset=utf-8',
363
+ 'Access-Control-Allow-Origin': '*',
364
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
365
+ 'Access-Control-Allow-Headers': 'Content-Type',
366
+ });
367
+ res.end(JSON.stringify(data, null, 2));
368
+ };
369
+ const server = createServer((req, res) => {
370
+ const url = new URL(req.url || '/', `http://localhost:${servePort}`);
371
+ if (req.method === 'OPTIONS') { sendJson(res, 204, {}); return; }
372
+ if (url.pathname === '/api/health') { sendJson(res, 200, { status: 'ok', version }); return; }
373
+ if (url.pathname !== '/api/guessit' && url.pathname !== '/') {
374
+ sendJson(res, 404, { error: 'Not found — use /api/guessit' });
375
+ return;
376
+ }
377
+ if (req.method === 'GET') {
378
+ const filename = url.searchParams.get('filename');
379
+ if (!filename) {
380
+ sendJson(res, 400, {
381
+ error: 'Missing required parameter: filename',
382
+ usage: `GET /api/guessit?filename=Movie.2020.1080p.mkv[&type=movie|episode] · POST /api/guessit {"filename": "..."} or {"filenames": ["..."]}`,
383
+ });
384
+ return;
385
+ }
386
+ const opts = { ...baseOptions };
387
+ const type = url.searchParams.get('type');
388
+ if (type === 'movie' || type === 'episode') opts.type = type;
389
+ try { sendJson(res, 200, display(guessit(filename, opts), 'json')); }
390
+ catch (e) { sendJson(res, 500, { error: String((e && e.message) || e) }); }
391
+ return;
392
+ }
393
+ if (req.method === 'POST') {
394
+ const chunks = [];
395
+ let size = 0;
396
+ req.on('data', (c) => { size += c.length; if (size > 1 << 20) req.destroy(); else chunks.push(c); });
397
+ req.on('end', () => {
398
+ try {
399
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
400
+ const opts = { ...baseOptions, ...(body.options || {}) };
401
+ if (Array.isArray(body.filenames)) {
402
+ sendJson(res, 200, body.filenames.map((f) => display(guessit(String(f), opts), 'json')));
403
+ } else if (typeof body.filename === 'string') {
404
+ sendJson(res, 200, display(guessit(body.filename, opts), 'json'));
405
+ } else {
406
+ sendJson(res, 400, { error: 'Body must contain "filename" (string) or "filenames" (array)' });
407
+ }
408
+ } catch (e) { sendJson(res, 400, { error: String((e && e.message) || e) }); }
409
+ });
410
+ return;
411
+ }
412
+ sendJson(res, 405, { error: 'Method not allowed' });
413
+ });
414
+ server.listen(servePort, () => {
415
+ console.log(`guessit-js ${version} API listening on http://localhost:${servePort}`);
416
+ console.log(` GET /api/guessit?filename=Movie.2020.1080p.mkv`);
417
+ console.log(` POST /api/guessit {"filename": "..."} or {"filenames": ["...", "..."]}`);
418
+ console.log(` GET /api/health`);
419
+ });
420
+ } else {
421
+
169
422
  // ---- main -------------------------------------------------------------------
170
423
  if (!process.stdin.isTTY && !filenames.length) {
171
424
  filenames.push(...readLines('-'));
172
425
  }
173
426
  if (!filenames.length) fail('usage: guessit-js [options] <filename> — see --help');
174
427
 
175
- // Advanced mode returns live Match objects; reduce them to the Python-CLI shape
176
- // ({value, raw, start, end}) instead of dumping engine internals.
177
- function simplifyAdvanced(v) {
178
- if (Array.isArray(v)) return v.map(simplifyAdvanced);
179
- if (v && typeof v === 'object' && 'start' in v && 'end' in v) {
180
- return { value: v.value, raw: v.raw, start: v.start, end: v.end };
428
+ if (benchmark > 0) {
429
+ guessit(filenames[0], options); // warm up (builds the pattern matcher)
430
+ const t0 = performance.now();
431
+ for (let n = 0; n < benchmark; n++) {
432
+ for (const f of filenames) guessit(f, options);
181
433
  }
182
- return v;
434
+ const elapsed = performance.now() - t0;
435
+ const total = benchmark * filenames.length;
436
+ console.log(`guessit-js ${version} benchmark`);
437
+ console.log(` ${total} parses (${filenames.length} filename${filenames.length > 1 ? 's' : ''} × ${benchmark} iterations)`);
438
+ console.log(` total: ${(elapsed / 1000).toFixed(2)} s`);
439
+ console.log(` per parse: ${(elapsed / total).toFixed(3)} ms`);
440
+ console.log(` throughput: ${Math.round(total / (elapsed / 1000))} parses/s`);
441
+ process.exit(0);
183
442
  }
184
443
 
185
444
  let hadError = false;
186
- const results = filenames.map((f) => {
445
+ for (const filename of filenames) {
446
+ let result;
187
447
  try {
188
- const r = guessit(f, options);
189
- if (!options.advanced) return r;
190
- const out = {};
191
- for (const [k, v] of Object.entries(r)) out[k] = simplifyAdvanced(v);
192
- return out;
448
+ const raw = guessit(filename, options);
449
+ if (options.advanced) {
450
+ result = {};
451
+ for (const [k, v] of Object.entries(raw)) result[k] = simplifyAdvanced(v);
452
+ } else {
453
+ result = display(raw, output === 'yaml' ? 'yaml' : 'json');
454
+ }
193
455
  } catch (e) {
194
456
  hadError = true;
195
- return { error: String(e && e.message || e) };
457
+ result = { error: String((e && e.message) || e) };
196
458
  }
197
- });
198
459
 
199
- if (showProperty) {
200
- results.forEach((r) => {
201
- const v = r[showProperty];
202
- console.log(v === undefined ? '' : typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v));
203
- });
204
- } else if (output === 'json') {
205
- console.log(JSON.stringify(filenames.length === 1 ? results[0] : results, null, 2));
206
- } else if (output === 'jsonl') {
207
- results.forEach((r) => console.log(JSON.stringify(r)));
208
- } else if (output === 'yaml') {
209
- results.forEach((r, i) => {
210
- if (filenames.length > 1) console.log(`${i ? '\n' : ''}? ${yamlScalar(filenames[i])}\n:`);
211
- console.log(toYaml(r, filenames.length > 1 ? ' ' : ''));
212
- });
213
- } else {
214
- results.forEach((r, i) => {
215
- if (i) console.log('');
216
- printLines(filenames[i], r, filenames.length > 1);
217
- });
460
+ if (verbose && output === 'default' && !showProperty) {
461
+ // Approximation of Python's rebulk debug log: one line per final match.
462
+ try {
463
+ const adv = guessit(filename, { ...options, advanced: true });
464
+ for (const [name, v] of Object.entries(adv)) {
465
+ for (const m of Array.isArray(v) ? v : [v]) {
466
+ if (m && typeof m === 'object' && 'start' in m) {
467
+ console.log(`Match found. (<${m.raw}:(${m.start}, ${m.end})+name=${name}>)`);
468
+ }
469
+ }
470
+ }
471
+ } catch { /* debug output is best-effort */ }
472
+ }
473
+
474
+ if (showProperty) {
475
+ const v = result[showProperty];
476
+ console.log(v === undefined ? '' : typeof v === 'object' && v !== null ? pyJson(v) : String(v));
477
+ } else if (output === 'json') {
478
+ console.log(pyJson(result));
479
+ } else if (output === 'yaml') {
480
+ console.log(`? ${yamlScalar(filename)}`);
481
+ const body = toYaml(result, ' ');
482
+ console.log(':' + body.slice(1));
483
+ } else {
484
+ console.log(`For: ${filename}`);
485
+ console.log(`GuessIt found: ${pyJsonIndent(result)}`);
486
+ }
218
487
  }
219
488
 
220
489
  process.exit(hadError ? 1 : 0);
490
+ } // end of non-serve mode
@@ -14516,7 +14516,7 @@ function configure(options, rulesBuilder, force = false) {
14516
14516
  function reset() {
14517
14517
  defaultApi.reset();
14518
14518
  }
14519
- const version$1 = "4.5.4";
14519
+ const version$1 = "4.7.0";
14520
14520
  const version = version$1;
14521
14521
  exports.GUESSIT_SCHEMA = GUESSIT_SCHEMA;
14522
14522
  exports.GuessItApi = GuessItApi;
@@ -14514,7 +14514,7 @@ function configure(options, rulesBuilder, force = false) {
14514
14514
  function reset() {
14515
14515
  defaultApi.reset();
14516
14516
  }
14517
- const version$1 = "4.5.4";
14517
+ const version$1 = "4.7.0";
14518
14518
  const version = version$1;
14519
14519
  export {
14520
14520
  GUESSIT_SCHEMA,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "guessit-js",
3
- "version": "4.5.4",
3
+ "version": "4.7.0",
4
4
  "description": "Extract metadata (title, year, season, episode, codec, language, etc.) from media filenames — TypeScript port of Python guessit",
5
5
  "keywords": [
6
6
  "guessit",
@@ -35,7 +35,8 @@
35
35
  "types": "./dist/index.d.ts",
36
36
  "sideEffects": false,
37
37
  "bin": {
38
- "guessit-js": "./bin/cli.mjs"
38
+ "guessit-js": "./bin/cli.mjs",
39
+ "guessit": "./bin/cli.mjs"
39
40
  },
40
41
  "engines": {
41
42
  "node": ">=18"