asciidoc-pubkit 0.8.0 → 0.8.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5e6439ccb97f49f7e31290cb8d60b1f361cf444889ac0631cdd1f9e28f8a0d9c
4
- data.tar.gz: 484ff3e7ac4475ea693ff7d5751bc34e1537b66dda90bb7d425bb55acb467322
3
+ metadata.gz: 8340a490160e7c0c2ca089657884c882eca5861dd27206dc9a3513ab1b5cfa2d
4
+ data.tar.gz: b4c2428c0408f2301563ee3e4586e9422c7b4875f927779146d9ebacec678568
5
5
  SHA512:
6
- metadata.gz: 9ccf0130e06770e7b12774385daab670fffde6a128e83af1d67300ada91ea6c15fc281645cfae6da6b7b009cca36d01429287ee36461c11f2d43c439d8307fe5
7
- data.tar.gz: f70b717d0633729647ac733670604e3d6ace15354efc31167f8af8994b62531ddba1c74f6456c293ccf16bbee4833ddbd2efb655c520151edee6b6559d94ca0c
6
+ metadata.gz: b919c53366fb83912221bf4a642b23db13725535c82449e54f6859d6a6bc76a04582c7b859eb4fb4f9cde814637dd535625eea31ffd62af48f02a6a71642c4f5
7
+ data.tar.gz: 18d123157532330403229b1365b97e2dcba308de2ed5d07aa16583c973d801bfa1e6aac001f299be7ab445beaf7a1600f204ff058362f1cd84dc7362f7466aca
data/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.1 — 2026-10-01
4
+
5
+ - Add an opening README feature table and describe prose replacements before
6
+ scoring and review.
7
+
8
+ - Support replacement regex `/i` with Ruby case-insensitive matching and translate
9
+ `\b`/`\B` assertions to limited ECMAScript Unicode word boundaries. Preserve
10
+ capture numbering, source positions, protected spans, and backspace-in-class
11
+ semantics; retain Ruby behavior elsewhere and reject other flags.
12
+
13
+ - Treat null replacement `rules`, including bare `rules:`, as an empty local
14
+ rule set while retaining imported rules and rejecting other non-array values.
15
+
16
+ - Accept nonempty string arrays in replacement `pattern` as an alias for
17
+ `patterns`, retaining strict validation, specs, protection, and conflict checks.
18
+
19
+ - Document omitted replacement `rules` as an empty set, including version-only
20
+ files, and verify CLI no-op behavior and application through import-only chains.
21
+
22
+ - Support nested local `imports` in replacement rules, resolving paths relative
23
+ to each importing file and accepting import-only files and `path` mappings.
24
+ Deduplicate physical files, reject cycles and unsupported import options, and
25
+ preserve validation, conflict detection, and prose-only replacement scope.
26
+
3
27
  ## 0.8.0 — 2026-10-01
4
28
 
5
29
  - Add explicit `replace check`, `replace diff`, and `replace apply` commands for
data/README.md CHANGED
@@ -7,13 +7,34 @@
7
7
 
8
8
  A toolkit for authoring and reviewing AsciiDoc books.
9
9
 
10
- Version 0.8.0 provides shared Japanese technical writing criteria, an authoring
10
+ Version 0.8.1 provides shared Japanese technical writing criteria, an authoring
11
11
  prompt, separate prose and heading review prompts, manuscript scoring, and
12
12
  baseline verification for edited manuscripts, plus explicit prose-only mechanical
13
13
  replacements using a limited prh-format rule set.
14
14
  The CLI, diagnostics, documentation, and generated instructions are in English.
15
15
  Japanese text is retained in manuscript excerpts, rule dictionaries, and fixtures.
16
16
 
17
+ ## Available features
18
+
19
+ The following commands are available in version 0.8.1.
20
+
21
+ | Feature | Commands | Behavior |
22
+ | --- | --- | --- |
23
+ | [Writing criteria and prompts](#writing-commands) | `writing criteria`, `writing prompt` | Print Japanese prose criteria or generate a writing prompt without a manuscript or MeCab |
24
+ | [Replacement preview](#prose-replacements) | `replace check`, `replace diff` | Report mechanical replacement candidates or preview a diff for mapped running prose; preserve source files |
25
+ | [Replacement application](#prose-replacements) | `replace apply` | Apply author-supplied rules after checking protected content and document structure; no MeCab or AI required |
26
+ | [Prose review](#review-workflow) | `review scan` | Collect mapped Japanese running prose and contextual review candidates with MeCab/IPADIC by default |
27
+ | [Heading review](#heading-review) | `review scan --scope headings` | Collect editable section titles separately, retaining the outline and read-only body evidence |
28
+ | [Review prompts](#prompt) | `review prompt` | Generate one Markdown prompt from a saved session for review and editing by an external reviewer |
29
+ | [Baseline verification](#verify) | `review verify` | Check edited sources against a saved baseline for mechanical preservation; meaning is not verified |
30
+ | [Manuscript scoring](#score-an-asciidoc-manuscript) | `review score` | Report a prose candidate-density score; explicit `--agent codex` or `--agent claude` optionally invokes a local AI CLI for readability ratings |
31
+
32
+ Version 0.8.1 additionally supports nested replacement-rule imports,
33
+ omitted/null `rules`, arrays in `pattern`, `/i`, and limited ECMAScript word
34
+ boundaries. See [Prose replacements](#prose-replacements) for supported syntax
35
+ and preservation limits. Only `replace apply` edits manuscripts directly;
36
+ review prompts supply instructions for an external reviewer.
37
+
17
38
  ## Status
18
39
 
19
40
  Version 0.6.3 adds separate heading review with `review scan --scope headings`.
@@ -86,7 +107,7 @@ Add the gem to your project's `Gemfile` to manage its version with Bundler:
86
107
 
87
108
  ```ruby
88
109
  source 'https://rubygems.org'
89
- gem 'asciidoc-pubkit', '~> 0.8.0'
110
+ gem 'asciidoc-pubkit', '~> 0.8.1'
90
111
  ```
91
112
 
92
113
  Then install dependencies and run the CLI through Bundler:
@@ -108,7 +129,7 @@ git clone https://github.com/cybergarage/asciidoc-pubkit.git
108
129
  cd asciidoc-pubkit
109
130
  bundle install
110
131
  gem build asciidoc-pubkit.gemspec
111
- gem install ./asciidoc-pubkit-0.8.0.gem
132
+ gem install ./asciidoc-pubkit-0.8.1.gem
112
133
  asciidoc-pubkit --version
113
134
  ```
114
135
 
@@ -132,12 +153,192 @@ asciidoc-pubkit writing prompt --lang ja --output writing-prompt.md
132
153
  ```
133
154
 
134
155
  For example, `--lang en` exits with an unsupported-language error. No English
135
- review or writing criteria are shipped in 0.8.0.
156
+ review or writing criteria are shipped in 0.8.1.
136
157
 
137
158
  For a small trial, use `examples/book.adoc` as the scan input. Its Japanese
138
159
  paragraphs deliberately contain review candidates; its code block must remain
139
160
  unchanged.
140
161
 
162
+ ## Prose replacements
163
+
164
+ Available starting with version 0.8.0.
165
+ It applies author-supplied mechanical replacement rules without MeCab or an AI
166
+ CLI. Review candidates and glossary variants remain advisory and are never
167
+ implicitly applied. Replacement rules are separate from review rules.
168
+
169
+ ```sh
170
+ asciidoc-pubkit replace check book.adoc --rules replacements.yml
171
+ asciidoc-pubkit replace diff book.adoc --rules replacements.yml
172
+ asciidoc-pubkit replace apply book.adoc --rules replacements.yml
173
+ ```
174
+
175
+ `check` reports original text, proposed text, rule IDs (`rule-1`, etc.), source
176
+ paths, one-based Unicode lines/columns, and a coverage-notice count. Its exit code
177
+ is 1 when replacements are available, 0 otherwise. `diff` previews unified diffs
178
+ without editing; it requires the external `diff` command. `apply` explicitly
179
+ authorizes source replacement without prompting. Successful diff/apply commands
180
+ return 0; invalid rules, conflicts, unsafe edits, and input/output failures return
181
+ 2. Check/diff accept `--output` for a new file only; apply rejects `--output`.
182
+
183
+ All three accept `--lang ja`, `--base-dir`, `--config`, and `--only` (an included
184
+ source file). Normal configuration discovery and `review.base_dir`, `language`,
185
+ `attributes`, and `exclude` control parsing and selection. `--rules` is required;
186
+ `review.rules` and glossary entries do not supply replacement rules. There are
187
+ no built-in replacement rules and no automatic search for `prh.yml`.
188
+
189
+ ### Limited prh-format rules
190
+
191
+ The supported format is a strict subset of [prh](https://github.com/prh/prh):
192
+
193
+ ```yaml
194
+ version: 1
195
+ rules:
196
+ - expected: '®'
197
+ pattern: '®'
198
+ - expected: '($1)'
199
+ pattern: '/(([^()\r\n]+))/'
200
+ specs:
201
+ - from: '設定(任意)'
202
+ to: '設定(任意)'
203
+ - expected: '/'
204
+ patterns:
205
+ - '/'
206
+ ```
207
+
208
+ The root requires `version: 1` and accepts optional `rules` and `imports` arrays.
209
+ Starting with version 0.8.1, omitted arrays default to empty. Version 0.8.0
210
+ requires `rules` and rejects `imports`. Each rule requires a string
211
+ `expected` (empty strings permit deletion) and exactly one of `pattern` (a
212
+ nonempty string or, starting with version 0.8.1, a nonempty array of nonempty
213
+ strings) or `patterns` (a nonempty array of nonempty strings). Array-valued
214
+ `pattern` is equivalent to `patterns`; specifying both keys is rejected. Optional
215
+ `specs` is an array of exact `from`/`to` string pairs, validated on load. Specs
216
+ exercise the rule on plain text, not AsciiDoc selection or inline protection.
217
+
218
+ Strings not beginning with `/` match literally. `/.../` denotes a regex; the
219
+ version 0.8.1 also accepts `/.../i` for Ruby case-insensitive matching.
220
+ Version 0.8.0 rejects all flags. All occurrences are collected. The implementation
221
+ uses Ruby regexes with
222
+ a timeout and accepts a limited common syntax: character classes, ordinary
223
+ captures, noncapturing groups, lookarounds, alternatives, anchors, quantifiers,
224
+ and the escapes `\n`, `\r`, `\t`, `\d`, `\D`, `\s`, `\S`, `\w`, `\W`
225
+ and escaped punctuation. Ruby regex character-class behavior applies; this is
226
+ not a JavaScript regex engine or a promise of full prh equivalence. Engine-specific
227
+ groups/escapes and flags other than a single `i` are rejected. A leading literal slash must be expressed
228
+ as an escaped regex, for example `/\//`. Zero-length matches are rejected.
229
+
230
+ Replacement strings support `$1` through `$99` for existing capture groups and
231
+ `$$` for a literal dollar sign. Unsupported dollar references are rejected when
232
+ matched. Missing optional captures expand to empty strings. YAML single quotes
233
+ are recommended to keep backslashes literal. Unknown fields, including
234
+ `options` and `regexpMustEmpty`, and omitted patterns are rejected rather than
235
+ ignored. prh's automatic pattern generation is not supported.
236
+
237
+ For example, version 0.8.1 also accepts:
238
+
239
+ ```yaml
240
+ version: 1
241
+ rules:
242
+ - expected: 'ハードウェア'
243
+ pattern:
244
+ - 'ハードウエア'
245
+ - 'ハードウェアー'
246
+ ```
247
+
248
+ Each array entry uses the same literal/regex syntax and validation as a single
249
+ pattern. Arrays do not change supported flags or overlap handling.
250
+
251
+ ### Limited ECMAScript boundary compatibility
252
+
253
+ Version 0.8.1 translates `\b` and `\B` outside character classes into Ruby
254
+ lookarounds with ECMAScript word-character semantics, following prh's default
255
+ Unicode mode. Word characters are ASCII letters, digits, and underscore; Japanese
256
+ characters are non-word characters. Thus `/\bTips\b/` matches `Tips` in
257
+ `前Tips後`, but not in `Tips2`, `_Tips`, or `ATips`.
258
+ With `/i`, long s (`ſ`) and Kelvin sign (`K`) also count as word characters under
259
+ ECMAScript Unicode case folding. The generated assertions add no capture groups
260
+ and preserve original match offsets. Inside a character class, `\b` means a
261
+ backspace character; `\B` there is rejected. Escaped literal backslashes are
262
+ preserved.
263
+
264
+ Only the boundary assertions emulate ECMAScript. `/i` uses Ruby's
265
+ `Regexp::IGNORECASE`; Unicode case folding can differ from JavaScript (for
266
+ example multi-character folds). Other constructs, including whitespace classes,
267
+ retain Ruby semantics. This is limited prh compatibility, not full ECMAScript
268
+ conformance. Flags `g`, `m`, `s`, `u`, `y`, `d`, and `v` and duplicate `i` are
269
+ rejected; all occurrences are already collected independently of `g`.
270
+
271
+ ### Importing replacement rules
272
+
273
+ Version 0.8.1 supports nested `imports`; version 0.8.0 does not. For example:
274
+
275
+ ```yaml
276
+ version: 1
277
+ imports:
278
+ - ../../rules/prh.yml
279
+ - path: ./terminology.yml
280
+ rules:
281
+ - expected: '®'
282
+ pattern: '®'
283
+ ```
284
+
285
+ Each entry is a nonempty local file path string or a mapping containing exactly
286
+ `path`. Relative paths resolve from the importing YAML file, including nested
287
+ imports, independently of the working directory and manuscript base directory.
288
+ Absolute local paths are also accepted; URL imports are rejected. An import-only
289
+ file may omit `rules`. A file containing only `version: 1` is also valid and
290
+ contributes no rules. With no imported or local rules, `check`, `diff`, and
291
+ `apply` succeed without changing manuscript sources, and `diff` emits no patch.
292
+ Starting with version 0.8.1, a bare `rules:`, `rules: null`, and `rules: ~`
293
+ also contribute no local rules, just like omission or `rules: []`; imported rules
294
+ are still loaded. Other non-array values remain invalid. This normalization
295
+ applies only to `rules`, not to `imports` or individual rule fields.
296
+ Every imported file must use version 1 and pass the same
297
+ strict rule validation and specs as the entry file.
298
+
299
+ Imports are loaded in listed order, recursively before each file's own rules.
300
+ Each physical file is loaded once per plan, including repeated paths, symlink
301
+ aliases, and shared dependencies. Rule IDs are assigned across the flattened
302
+ set. Cycles (including symlink aliases), missing files, and import chains deeper
303
+ than 100 files fail rather than silently omitting rules. Imported and local rules
304
+ are combined, not overridden: overlapping replacement candidates remain errors
305
+ and replacements are still calculated only against the original text.
306
+
307
+ Import options such as `ignoreRules` and `disableImports` remain unsupported and
308
+ are rejected. Source selection and protection are unchanged by imports.
309
+
310
+ ### Selection and preservation
311
+
312
+ Only unambiguously source-mapped running prose in the existing default review
313
+ scope is eligible. Headings, lists, tables, quotations, listing/source, literal,
314
+ and passthrough blocks are excluded. Recognized inline code, quotations, URLs,
315
+ macros, and attribute references are protected by the existing conservative
316
+ inline heuristic, not a complete inline parser. A match overlapping any protected
317
+ span is skipped; matching is performed on the original text, never on blanked
318
+ placeholders. Backtick-to-bold and list-marker conversions are outside this scope.
319
+
320
+ Candidates are calculated once against the original sources; replacement results
321
+ are not searched again. Overlapping edits are conflicts, not resolved by rule
322
+ order. Matches/results containing line breaks are rejected. Source files retain
323
+ UTF-8 bytes, original line endings, and unrelated content; repeated include
324
+ occurrences must not create overlapping edits.
325
+
326
+ Before presenting a plan, the complete captured source set is copied to temporary
327
+ staging and reparsed. Parsing diagnostics, structural changes, new/deleted protected
328
+ inline tokens, and protected-content/source-membership changes reject the plan.
329
+ Relative includes within the base directory are supported. Absolute includes and
330
+ includes whose paths depend on the original filesystem may fail staged validation;
331
+ they are not rewritten or silently accepted. Symlink entrypoints are rejected.
332
+
333
+ Apply stages all changed files beside their destinations, checks all captured
334
+ source bytes against the plan, and renames the prepared files into place while
335
+ preserving permission bits. An ordinary installation error restores sources
336
+ already installed. This is not a crash-atomic transaction across multiple files;
337
+ keep manuscripts under version control and avoid concurrent edits during apply.
338
+ No review session is created or replaced. Existing sessions retain their original
339
+ baselines; applying replacements can make a session stale for prompt generation.
340
+ Mechanical validation does not establish semantic correctness.
341
+
141
342
  ## Score an AsciiDoc manuscript
142
343
 
143
344
  Pass any AsciiDoc entry file directly; no review session or gold annotations are
@@ -753,107 +954,6 @@ Regex patterns are not interpreted in glossary or allow-list entries. Unknown
753
954
  configuration keys are rejected. A bare `mecab_command` is resolved through PATH;
754
955
  use an absolute path for an explicit executable override.
755
956
 
756
- ## Prose replacements
757
-
758
- Available starting with version 0.8.0.
759
- It applies author-supplied mechanical replacement rules without MeCab or an AI
760
- CLI. Review candidates and glossary variants remain advisory and are never
761
- implicitly applied. Replacement rules are separate from review rules.
762
-
763
- ```sh
764
- asciidoc-pubkit replace check book.adoc --rules replacements.yml
765
- asciidoc-pubkit replace diff book.adoc --rules replacements.yml
766
- asciidoc-pubkit replace apply book.adoc --rules replacements.yml
767
- ```
768
-
769
- `check` reports original text, proposed text, rule IDs (`rule-1`, etc.), source
770
- paths, one-based Unicode lines/columns, and a coverage-notice count. Its exit code
771
- is 1 when replacements are available, 0 otherwise. `diff` previews unified diffs
772
- without editing; it requires the external `diff` command. `apply` explicitly
773
- authorizes source replacement without prompting. Successful diff/apply commands
774
- return 0; invalid rules, conflicts, unsafe edits, and input/output failures return
775
- 2. Check/diff accept `--output` for a new file only; apply rejects `--output`.
776
-
777
- All three accept `--lang ja`, `--base-dir`, `--config`, and `--only` (an included
778
- source file). Normal configuration discovery and `review.base_dir`, `language`,
779
- `attributes`, and `exclude` control parsing and selection. `--rules` is required;
780
- `review.rules` and glossary entries do not supply replacement rules. There are
781
- no built-in replacement rules and no automatic search for `prh.yml`.
782
-
783
- ### Limited prh-format rules
784
-
785
- The supported format is a strict subset of [prh](https://github.com/prh/prh):
786
-
787
- ```yaml
788
- version: 1
789
- rules:
790
- - expected: '®'
791
- pattern: '®'
792
- - expected: '($1)'
793
- pattern: '/(([^()\r\n]+))/'
794
- specs:
795
- - from: '設定(任意)'
796
- to: '設定(任意)'
797
- - expected: '/'
798
- patterns:
799
- - '/'
800
- ```
801
-
802
- The root contains exactly `version: 1` and `rules`. Each rule requires a string
803
- `expected` (empty strings permit deletion) and exactly one of `pattern` (a
804
- nonempty string) or `patterns` (a nonempty array of nonempty strings). Optional
805
- `specs` is an array of exact `from`/`to` string pairs, validated on load. Specs
806
- exercise the rule on plain text, not AsciiDoc selection or inline protection.
807
-
808
- Strings not beginning with `/` match literally. `/.../` denotes a regex with no
809
- flags; all occurrences are collected. The implementation uses Ruby regexes with
810
- a timeout and accepts a limited common syntax: character classes, ordinary
811
- captures, noncapturing groups, lookarounds, alternatives, anchors, quantifiers,
812
- and the escapes `\n`, `\r`, `\t`, `\d`, `\D`, `\s`, `\S`, `\w`, `\W`
813
- and escaped punctuation. Ruby regex character-class behavior applies; this is
814
- not a JavaScript regex engine or a promise of full prh equivalence. Engine-specific
815
- groups/escapes and flags are rejected. A leading literal slash must be expressed
816
- as an escaped regex, for example `/\//`. Zero-length matches are rejected.
817
-
818
- Replacement strings support `$1` through `$99` for existing capture groups and
819
- `$$` for a literal dollar sign. Unsupported dollar references are rejected when
820
- matched. Missing optional captures expand to empty strings. YAML single quotes
821
- are recommended to keep backslashes literal. Unknown fields, including `imports`,
822
- `options`, and `regexpMustEmpty`, and omitted patterns are rejected rather than
823
- ignored. Regex flags and prh's automatic pattern generation are not supported.
824
-
825
- ### Selection and preservation
826
-
827
- Only unambiguously source-mapped running prose in the existing default review
828
- scope is eligible. Headings, lists, tables, quotations, listing/source, literal,
829
- and passthrough blocks are excluded. Recognized inline code, quotations, URLs,
830
- macros, and attribute references are protected by the existing conservative
831
- inline heuristic, not a complete inline parser. A match overlapping any protected
832
- span is skipped; matching is performed on the original text, never on blanked
833
- placeholders. Backtick-to-bold and list-marker conversions are outside this scope.
834
-
835
- Candidates are calculated once against the original sources; replacement results
836
- are not searched again. Overlapping edits are conflicts, not resolved by rule
837
- order. Matches/results containing line breaks are rejected. Source files retain
838
- UTF-8 bytes, original line endings, and unrelated content; repeated include
839
- occurrences must not create overlapping edits.
840
-
841
- Before presenting a plan, the complete captured source set is copied to temporary
842
- staging and reparsed. Parsing diagnostics, structural changes, new/deleted protected
843
- inline tokens, and protected-content/source-membership changes reject the plan.
844
- Relative includes within the base directory are supported. Absolute includes and
845
- includes whose paths depend on the original filesystem may fail staged validation;
846
- they are not rewritten or silently accepted. Symlink entrypoints are rejected.
847
-
848
- Apply stages all changed files beside their destinations, checks all captured
849
- source bytes against the plan, and renames the prepared files into place while
850
- preserving permission bits. An ordinary installation error restores sources
851
- already installed. This is not a crash-atomic transaction across multiple files;
852
- keep manuscripts under version control and avoid concurrent edits during apply.
853
- No review session is created or replaced. Existing sessions retain their original
854
- baselines; applying replacements can make a session stale for prompt generation.
855
- Mechanical validation does not establish semantic correctness.
856
-
857
957
  ## Rules and coverage
858
958
 
859
959
  | Rule | Severity | Purpose |
@@ -944,12 +1044,12 @@ reports analyzer changes instead of treating results from different dictionaries
944
1044
  as directly comparable. Prompt generation uses saved evidence and does not need
945
1045
  MeCab. Changed rules or dictionary settings require a new scan.
946
1046
 
947
- Sessions from earlier tool versions are not compatible with 0.8.0 (session schema 2). Keep the original baseline for
1047
+ Sessions from earlier tool versions are not compatible with 0.8.1 (session schema 2). Keep the original baseline for
948
1048
  an ongoing review and finish it with the original version, or start a new review
949
1049
  pass in a different directory:
950
1050
 
951
1051
  ```sh
952
- asciidoc-pubkit review scan book.adoc --output .pubkit/review-0.8.0
1052
+ asciidoc-pubkit review scan book.adoc --output .pubkit/review-0.8.1
953
1053
  ```
954
1054
 
955
1055
  Severity describes review priority, not proof of an error. There is no AI-authorship
@@ -7,30 +7,31 @@ require 'open3'
7
7
  module AsciidocPubkit
8
8
  class ReplacementRules
9
9
  def self.load(path)
10
- data = YAML.safe_load(AsciidocPubkit.read_text(path), permitted_classes: [], aliases: false)
11
- RuleSet.mapping(data, %w[version rules], 'Replacement rules')
12
- raise Error, 'Replacement version must be integer 1.' unless data['version'].is_a?(Integer) && data['version'] == 1
13
- raise Error, 'rules must be an array.' unless data['rules'].is_a?(Array)
14
- data['rules'].each_with_index.map do |rule, index|
10
+ collect(path, [], {}).each_with_index.map do |rule, index|
15
11
  unless rule.is_a?(Hash) && (rule.keys - %w[expected pattern patterns specs]).empty? &&
16
12
  rule['expected'].is_a?(String) && (rule.key?('pattern') ^ rule.key?('patterns'))
17
13
  raise Error, "Rule #{index + 1} requires expected and exactly one of pattern or patterns; unsupported keys are rejected."
18
14
  end
19
- patterns = rule.key?('pattern') ? [rule['pattern']] : rule['patterns']
15
+ patterns = rule.key?('pattern') ? rule['pattern'] : rule['patterns']
16
+ patterns = [patterns] if rule.key?('pattern') && patterns.is_a?(String)
20
17
  unless patterns.is_a?(Array) && !patterns.empty? && patterns.all? { |p| p.is_a?(String) && !p.empty? }
21
18
  raise Error, 'Replacement patterns must be nonempty strings.'
22
19
  end
23
20
  compiled = patterns.map do |pattern|
24
21
  if pattern.start_with?('/')
25
22
  match = pattern.match(%r{\A/(.*)/([a-z]*)\z}m)
26
- raise Error, 'Regex flags are unsupported; omit flags (all matches are collected).' unless match && match[2].empty?
23
+ unless match && ['', 'i'].include?(match[2])
24
+ raise Error, 'Unsupported regex flags; only optional i is supported (all matches are collected).'
25
+ end
27
26
  body = match[1]
28
27
  # Deliberately small common JavaScript/Ruby subset; Ruby-only escapes
29
28
  # and engine-specific groups must not silently change JS semantics.
30
- if body.match?(/\\[^\\\/.*+?()\[\]{}^$|nrtdDsSwW-]/) || body.match?(/\(\?(?![:=!]|<[=!])/) || body.include?('&&')
29
+ if body.match?(/\\[^\\\/.*+?()\[\]{}^$|nrtdDsSwWbB-]/) || body.match?(/\(\?(?![:=!]|<[=!])/) || body.include?('&&')
31
30
  raise Error, 'Unsupported regex syntax in replacement rule.'
32
31
  end
33
- Regexp.new(body.gsub('\\/', '/'), timeout: 0.1)
32
+ ignore_case = match[2] == 'i'
33
+ body = javascript_boundaries(body, ignore_case: ignore_case)
34
+ Regexp.new(body.gsub('\\/', '/'), ignore_case ? Regexp::IGNORECASE : 0, timeout: 0.1)
34
35
  else
35
36
  Regexp.new(Regexp.escape(pattern), timeout: 0.1)
36
37
  end
@@ -56,6 +57,75 @@ module AsciidocPubkit
56
57
  raise Error, "Invalid replacement regex: #{e.message}"
57
58
  end
58
59
 
60
+ # prh uses Unicode JS regexes: word characters are ASCII letters/digits/_;
61
+ # Unicode ignore-case additionally folds long s and Kelvin sign to ASCII.
62
+ # Scope out Ruby's ignore-case so these assertion classes stay exact.
63
+ def self.javascript_boundaries(body, ignore_case:)
64
+ word = ignore_case ? '(?-i:[A-Za-z0-9_ſK])' : '[A-Za-z0-9_]'
65
+ boundary = "(?:(?<=#{word})(?!#{word})|(?<!#{word})(?=#{word}))"
66
+ nonboundary = "(?:(?<=#{word})(?=#{word})|(?<!#{word})(?!#{word}))"
67
+ chars = body.chars
68
+ result = +''
69
+ in_class = false
70
+ index = 0
71
+ while index < chars.length
72
+ char = chars[index]
73
+ if char == '\\' && index + 1 < chars.length
74
+ following = chars[index + 1]
75
+ if following == 'b'
76
+ result << (in_class ? '\x08' : boundary)
77
+ elsif following == 'B'
78
+ raise Error, '\B inside a character class is unsupported.' if in_class
79
+ result << nonboundary
80
+ else
81
+ result << char << following
82
+ end
83
+ index += 2
84
+ next
85
+ end
86
+ in_class = true if char == '['
87
+ in_class = false if char == ']'
88
+ result << char
89
+ index += 1
90
+ end
91
+ result
92
+ end
93
+
94
+ def self.collect(path, active, visited)
95
+ path = File.realpath(path)
96
+ if active.include?(path)
97
+ raise Error, "Circular replacement imports: #{(active + [path]).join(' -> ')}"
98
+ end
99
+ return [] if visited[path]
100
+ raise Error, 'Replacement imports exceed the maximum depth of 100 files.' if active.length >= 100
101
+ data = YAML.safe_load(AsciidocPubkit.read_text(path), permitted_classes: [], aliases: false)
102
+ unless data.is_a?(Hash) && data.key?('version') && (data.keys - %w[version rules imports]).empty?
103
+ raise Error, "Replacement rules in #{path} require version and accept only rules and imports."
104
+ end
105
+ unless data['version'].is_a?(Integer) && data['version'] == 1
106
+ raise Error, "Replacement version in #{path} must be integer 1."
107
+ end
108
+ rules = data.fetch('rules', [])
109
+ rules = [] if rules.nil?
110
+ imports = data.fetch('imports', [])
111
+ raise Error, "rules in #{path} must be an array." unless rules.is_a?(Array)
112
+ raise Error, "imports in #{path} must be an array." unless imports.is_a?(Array)
113
+ imported = imports.flat_map do |entry|
114
+ if entry.is_a?(Hash)
115
+ RuleSet.mapping(entry, ['path'], "Replacement import in #{path}")
116
+ entry = entry['path']
117
+ end
118
+ unless entry.is_a?(String) && !entry.strip.empty? && !entry.match?(/\A[a-z][a-z0-9+.-]*:/i)
119
+ raise Error, "Replacement imports in #{path} must specify nonempty local file paths."
120
+ end
121
+ collect(File.expand_path(entry, File.dirname(path)), active + [path], visited)
122
+ end
123
+ visited[path] = true
124
+ imported + rules
125
+ rescue Psych::Exception => e
126
+ raise Error, "Invalid replacement YAML in #{path}: #{e.message}"
127
+ end
128
+
59
129
  def self.expand(template, match)
60
130
  template.gsub(/\$\$|\$[1-9][0-9]?|\$./) do |ref|
61
131
  if ref == '$$'
@@ -9,7 +9,7 @@ require 'pathname'
9
9
  require 'optparse'
10
10
 
11
11
  module AsciidocPubkit
12
- VERSION = '0.8.0'
12
+ VERSION = '0.8.1'
13
13
  class Error < StandardError; end
14
14
 
15
15
  def self.hash_text(text)
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: asciidoc-pubkit
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.0
4
+ version: 0.8.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - CyberGarage