lightward_liquid_ext 1.0.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ebd0cfb3680107e9a9998f68ff5171dfc6cdcb963ce55454912f49268d29c423
4
+ data.tar.gz: a4d84f43871219feb4c56c32e53c21c005b92c72a0ee5085434e12824e8b652e
5
+ SHA512:
6
+ metadata.gz: 29fbaa5ea50131192abde4cddfa5067c05d37fd62c2d39af1a091cf5889d6c1c93e4db97fc0033c33a5ae18492f0c66932ac1c0a4b6f36aba8c37e56673df86e
7
+ data.tar.gz: 719fcb54ed81f35ba5dec4f47813909840606866a5d2f8b1416fdee46caf19ca3cb3c688aaf02f95d3252e906d7294a9a15034b44790c0e1824db592d0866adc
data/README.md ADDED
@@ -0,0 +1,219 @@
1
+ # lightward_liquid_ext
2
+
3
+ A few additions to [Shopify's Liquid](https://github.com/Shopify/liquid), so a template can build its own data: hashes and arrays you can fill in key by key, a `newline` you can split and join by, and regular expressions for pulling strings apart.
4
+
5
+ These come from [Mechanic](https://mechanic.dev), Lightward's automation platform for Shopify, where every task is written in Liquid. They run there in the tasks of real Shopify stores, parts of them since 2018. This gem is taken from that code, with some changes, so anyone using Liquid can have it. It stands on plain Liquid, with no Rails, and differs from Mechanic's Liquid in these ways:
6
+
7
+ - Assignment copies by value all the way down, including a plain `{% assign copy = original %}` and a hash or array handed to a `render` partial.
8
+ - An array assignment may add at most 100,000 empty slots past the end (`max_array_gap`, below).
9
+ - Hashes and arrays nest at most 100 levels deep, for assignment and for `json`.
10
+ - `first` and `last` on a match give its first and last characters, without needing ActiveSupport.
11
+ - The keywords `array`, `hash` and `newline` apply only in environments you install the gem into.
12
+ - Regular expressions run under a per-match timeout, `scan` counts against `render_score_limit`, and `parse_json` errors quote only the start of the input.
13
+
14
+ ## Before you install: two things to know
15
+
16
+ **The three keywords take over three names.** In an environment where the gem is installed, `hash`, `array` and `newline` always mean the keyword literals. If your existing templates read a variable you pass in under one of those names (`{{ hash }}`, `{{ hash.secret }}`, `{% for x in array %}`), they'll see the literal instead once you install: every lookup rooted at one of these names resolves against the literal. Rename those variables first, or install into a separate environment for the templates that want the keywords. Environments you don't install into are untouched.
17
+
18
+ **If people you don't trust write your templates, set limits.** Liquid's own defaults set none, and this gem adds tags and filters that can allocate a lot in one step. One guard is always on: an array assignment may add at most `LightwardLiquidExt.max_array_gap` empty slots past the end (100,000 by default; raise it, or set `nil` to turn it off), so `{% assign a[1000000000] = 1 %}` is refused before anything is allocated. Liquid's three limits bound most of the rest. A regular expression timeout bounds each match. Neither bounds wall-clock time across a whole render, so add a deadline too:
19
+
20
+ ```ruby
21
+ require "lightward_liquid_ext"
22
+
23
+ environment = Liquid::Environment.build do |env|
24
+ LightwardLiquidExt.install!(env)
25
+ env.default_resource_limits = {
26
+ render_score_limit: 100_000, # nodes rendered (a loop body on every pass), plus each match scan finds
27
+ assign_score_limit: 100_000, # bytes and items assigned, including empty array slots
28
+ render_length_limit: 1_000_000, # bytes of output
29
+ }
30
+ end
31
+
32
+ LightwardLiquidExt.regexp_timeout = 0.5 # seconds per match; the default is 1.0
33
+
34
+ # Checked at every assign. Raising a Liquid::MemoryError stops the render.
35
+ LightwardLiquidExt.assign_hook = ->(context) do
36
+ deadline = context.registers[:deadline]
37
+ raise(Liquid::MemoryError, "Render took too long") if deadline && Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
38
+ end
39
+
40
+ template = Liquid::Template.parse(source, environment: environment)
41
+ template.render(assigns, registers: { deadline: Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 })
42
+ ```
43
+
44
+ What these don't cover, and what's left to you as the host:
45
+
46
+ - The regexp timeout bounds one match, not a render. A loop of slow matches costs the timeout once per match, and a non-raising `render` records each timeout and carries on. Ruby 3.2+ memoizes most backtracking away (`(a+)+b` is fast), but not patterns with lookarounds or backreferences, so those are the ones that reach the timeout. Bounding the render as a whole is the host's job.
47
+ - `assign_hook` is one setting for the whole process, not per environment or per render, so a host serving several kinds of template decides inside the hook what applies (registers are a good place to carry that). It runs only at `assign`. A template that loops over `match` without assigning never reaches it. For a hard bound, also run renders under your own wall-clock and memory limits (a worker process you can stop, for instance).
48
+ - Single filter calls on large input, in this gem and in Liquid itself (`(1..1000000000) | join`, `json` on a huge value, `scan` on a multi-megabyte string you passed in) do their work before any limit is checked. `scan` counts each match against `render_score_limit` as it goes, so it stops at the limit, but it still holds the matches it has found until then.
49
+
50
+ ## What it adds
51
+
52
+ ### `array`, `hash` and `newline`
53
+
54
+ Three keyword literals, usable anywhere Liquid takes a value:
55
+
56
+ ```liquid
57
+ {% assign tags = array %}
58
+ {% assign tags = tags | push: "vip" | push: "wholesale" %}
59
+
60
+ {% assign customer = hash %}
61
+ {% assign customer["name"] = "Alice" %}
62
+
63
+ {% assign lines = some_text | split: newline %}
64
+ {{ lines | join: newline }}
65
+ ```
66
+
67
+ They're literals, like Liquid's own `true` and `nil`: `{% assign hash = "x" %}` succeeds, but doesn't change what `hash` means afterwards, and a variable passed in under one of these names can't be read (see above). Each assignment gets an empty hash or array of its own. They take filters (`{{ array | size }}`), and lookups on them resolve against the literal: `{{ array.size }}` is 0, and `{{ hash.anything }}` or `{{ hash["anything"] }}` is empty.
68
+
69
+ ### Assigning into hashes and arrays
70
+
71
+ `assign` can set a key in a hash or an index in an array, inside hashes and arrays that already exist:
72
+
73
+ ```liquid
74
+ {% assign sizes = hash %}
75
+ {% assign sizes["S"] = "Small" %}
76
+ {% assign key = "M" %}
77
+ {% assign sizes[key] = "Medium" %}
78
+
79
+ {% assign weekdays = array %}
80
+ {% assign weekdays[0] = "Monday" %}
81
+ {% assign weekdays[weekdays.size] = "Tuesday" %}
82
+
83
+ {% assign report = hash %}
84
+ {% assign report["by_day"] = array %}
85
+ {% assign report["by_day"][0] = sizes %}
86
+
87
+ {{ report | json }}
88
+ ```
89
+
90
+ The rules:
91
+
92
+ - Assignment is always by value. What you assign is copied, all the way down, so changing it later never changes anything else, and changing anything else never changes it. That includes a plain `{% assign copy = original %}`: assigning into `copy` afterwards leaves `original` alone. It holds across `render` too: a partial that assigns into a hash it was given changes its own copy, not the caller's.
93
+ - Copying has a cost: every plain `assign` of a hash or array copies the whole of it, so re-assigning a large collection in a loop costs its size each time (stock Liquid's assign is constant-time). `assign_score_limit` counts it.
94
+ - Intermediate keys must already exist; nothing is created along the way. `{% assign h["a"]["b"] = 1 %}` needs `h["a"]` to be a hash first (`{% assign h["a"] = hash %}`).
95
+ - Hashes and arrays nest at most 100 levels deep (the JSON library's own default). Going deeper, by assignment or with `json`, is refused with a plain error.
96
+ - Only hashes and arrays made with `assign` accept assignments: from `hash`, `array`, or a filter like `split` or `parse_json`. Variables the host passed in as the template's data can't be assigned into (assign a new hash or array over them first), and neither can strings or other objects. A hash or array that reaches a template another way, as an argument to a `render` partial or in a context's outer scope, is copied on its first change instead, so the original is never touched; a Hash or Array subclass there (a `HashWithIndifferentAccess`, say) becomes a plain Hash or Array in the copy. A `for` loop variable or an `include` parameter can't be assigned into either: copy it into a variable of your own first (`{% assign my_item = item %}`).
97
+ - Hashes take string keys. Arrays take integer indexes; a negative index counts from the end, within the array's length.
98
+ - Use brackets, not dots, on the left side: `{% assign foo.bar = 1 %}` is refused with a suggestion to write `{% assign foo["bar"] = 1 %}`. Lookups inside the brackets can be quoted strings or variables (`foo[key]`, `foo[foo.size]`), but not further bracket lookups (`foo[bar[0]]`), and there's no space inside the brackets.
99
+ - Assignments count against Liquid's `assign_score_limit`, the same way Liquid's own assign does. Assigning far past the end of an array counts every empty slot it creates.
100
+
101
+ Mechanic's documentation covers this in more depth: [assign](https://learn.mechanic.dev/platform/liquid/tags/assign) and [keyword literals](https://learn.mechanic.dev/platform/liquid/keyword-literals).
102
+
103
+ ### `split` and `replace` with `newline`
104
+
105
+ Given the `newline` literal itself, `split` and `replace` match `"\r\n"` as well as `"\n"`, so text from Windows, email and spreadsheets splits cleanly:
106
+
107
+ ```liquid
108
+ {% assign lines = pasted_text | split: newline %}
109
+ {% assign one_line = pasted_text | replace: newline, ", " %}
110
+ ```
111
+
112
+ Given anything else, both filters behave exactly as Liquid's own. (Liquid's `newline_to_br` already handles `"\r\n"`.) See [newline](https://learn.mechanic.dev/platform/liquid/keyword-literals/newline).
113
+
114
+ ### `match` and `scan`
115
+
116
+ Regular expressions, written as Ruby-compatible pattern strings:
117
+
118
+ ```liquid
119
+ {{ "It's a lovely day!" | match: "(?<=a ).*(?= day)" }}
120
+ => lovely
121
+
122
+ {% assign m = "It's a lovely day!" | match: "a (?<adjective>bucolic|lovely) day" %}
123
+ {{ m.captures | json }} => ["lovely"]
124
+ {{ m.named_captures | json }} => {"adjective":"lovely"}
125
+
126
+ {{ "It's a lovely day!" | scan: "[\w']+" | json }}
127
+ => ["It's","a","lovely","day"]
128
+
129
+ {{ "It's a lovely day!" | scan: "(bucolic|lovely|day)" | map: "captures" | json }}
130
+ => [["lovely"],["day"]]
131
+ ```
132
+
133
+ `match` returns the first match, or nil. `scan` returns every match. A match renders as the matched text and behaves like it for string filters and for `size`, `first` and `last` (its length, first character and last character), with `captures` and `named_captures` for the groups. Matches don't sort; `map` them to strings first. There's no `m[0]` or `m["name"]`: Liquid reads `m.foo` and `m["foo"]` as the same lookup, so asking for the captures by name keeps it clear what you're getting. See [match](https://learn.mechanic.dev/platform/liquid/filters#match) and [scan](https://learn.mechanic.dev/platform/liquid/filters#scan).
134
+
135
+ Each match gives up after `LightwardLiquidExt.regexp_timeout` seconds (1.0 by default; `nil` inherits Ruby's process-wide `Regexp.timeout`, which is no limit unless you set one) with an error saying so. Compiled patterns are reused, up to a hundred at a time.
136
+
137
+ ### `push`, `unshift`, `json` and `parse_json`
138
+
139
+ ```liquid
140
+ {% assign list = array | push: "b", "c" | unshift: "a" %}
141
+ {{ list | json }} => ["a","b","c"]
142
+
143
+ {% assign data = '{"items": [1, 2]}' | parse_json %}
144
+ {% assign maybe = untrusted_text | parse_json: silent: true %}
145
+ ```
146
+
147
+ `push` and `unshift` return a new array and leave the original alone. `parse_json` with `silent: true` gives nil for invalid JSON instead of an error; without it, the error gives the line and column where parsing failed (when the JSON parser reports them) and the first 80 characters of the input, and nothing else from the input. An object can choose its own JSON form for `json` by responding to `as_liquid_json`. See [json, parse_json](https://learn.mechanic.dev/platform/liquid/filters#json-parse_json).
148
+
149
+ ## Installing
150
+
151
+ ```ruby
152
+ # Gemfile
153
+ gem "lightward_liquid_ext"
154
+ ```
155
+
156
+ Or straight from the source:
157
+
158
+ ```ruby
159
+ gem "lightward_liquid_ext", git: "https://github.com/lightward/liquid-ext"
160
+ # or, with a local checkout:
161
+ gem "lightward_liquid_ext", path: "../liquid-ext"
162
+ ```
163
+
164
+ ```ruby
165
+ require "lightward_liquid_ext"
166
+
167
+ LightwardLiquidExt.install! # Liquid::Environment.default
168
+ ```
169
+
170
+ Or for an environment of your own (`Liquid::Environment.build` freezes what it builds, so install inside the block):
171
+
172
+ ```ruby
173
+ environment = Liquid::Environment.build do |env|
174
+ LightwardLiquidExt.install!(env)
175
+ end
176
+
177
+ Liquid::Template.parse(source, environment: environment).render!(assigns)
178
+ ```
179
+
180
+ `install!` registers the `assign` tag and the filters on the environment you give it, turns on the keyword literals for templates parsed and rendered in it, and is safe to call more than once. Other environments are untouched, and requiring the gem changes nothing until you call it.
181
+
182
+ ### A hook on every assign
183
+
184
+ ```ruby
185
+ LightwardLiquidExt.assign_hook = ->(context) { Thread.pass }
186
+ ```
187
+
188
+ If set, it's called with the `Liquid::Context` at the start of every `assign`. If it raises, that assign doesn't happen. What happens next depends on what it raises:
189
+
190
+ - A `Liquid::MemoryError` stops the render, under `render` and `render!` alike. Use it to stop a render.
191
+ - Under `render!`, anything it raises stops the render and reaches you.
192
+ - Under a non-raising `render`, any other `Liquid::Error` is recorded in `template.errors` with its own message, and the render carries on. Any error that isn't a `Liquid::Error` is recorded there as `Liquid::InternalError` ("Liquid error: internal"), with the original kept only as that error's `cause`, and the render carries on. So raise a `Liquid::Error` subclass if you want the reason to show. (In lax and strict mode the message isn't written into the output, since `assign` writes nothing; in strict2 it is.)
193
+
194
+ A host can use it to give other threads a turn, check a deadline, or count work. It's `nil` by default, and it's one setting for the whole process.
195
+
196
+ ## Which Liquid
197
+
198
+ Versions follow semver, counted from 1.0.0 on the first release: the number describes the change that comes after, not a verdict on the start, so a breaking change is 2.0.
199
+
200
+ This gem targets Liquid 5.14 (the current release as of November 2026) and follows current Liquid: the gemspec allows `>= 5.14, < 6`, and new Liquid releases are what it moves toward. Most of the specs run in Liquid's default parse mode, `lax`; one renders the keyword literals and bracket assignment in each of `lax`, `warn`, `strict` and `strict2`, and another checks the literals in `strict2` in an environment without the gem. On install, it checks the Liquid version and the shape of the few Liquid methods it extends (`Liquid::ParseContext#parse_expression` and `#safe_parse_expression`, and `Liquid::Context#[]`), and raises `LightwardLiquidExt::IncompatibleLiquidError` with a pointer back here if either isn't what it expects.
201
+
202
+ The specs pass on Ruby 3.4 and 4.0, and the gemspec asks for Ruby 3.4 or later.
203
+
204
+ It depends on `base64` because Liquid 5.14 requires it without declaring it, and Ruby 3.4 stopped shipping it by default.
205
+
206
+ ## Prior art
207
+
208
+ Shopify has explored array literals in Liquid itself: [Shopify/liquid#2134](https://github.com/Shopify/liquid/pull/2134) (closed), a research draft adding a bracketed syntax (`['top', 'bottom']`) to the expression grammar. This gem takes a different, smaller route (keyword literals plus assignment by key and index), the one Mechanic has used.
209
+
210
+ ## Development
211
+
212
+ ```sh
213
+ bundle install
214
+ bundle exec rspec
215
+ ```
216
+
217
+ ## License
218
+
219
+ Public domain, under the [Unlicense](UNLICENSE).
data/UNLICENSE ADDED
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <https://unlicense.org/>
@@ -0,0 +1,264 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ # Liquid's assign tag, extended to assign into hashes and arrays:
5
+ #
6
+ # {% assign foo = 'monkey' %}
7
+ # {% assign bar = hash %}
8
+ # {% assign bar["baz"] = 'monkey' %}
9
+ # {% assign list = array %}
10
+ # {% assign list[list.size] = 'monkey' %}
11
+ # {% assign bar["nested"] = hash %}
12
+ # {% assign bar["nested"]["deeper"] = list %}
13
+ #
14
+ # Assignment is always by value. Whatever lands in a variable, or inside a hash
15
+ # or array, is a copy: changing it later never changes anything else, and
16
+ # changing anything else never changes it.
17
+ #
18
+ # Only hashes and arrays made in the template (with `hash`, `array`, or a filter
19
+ # like `split` or `parse_json`) accept assignments. Hashes take string keys,
20
+ # arrays take integer indexes, and dot lookups on the left side are refused
21
+ # with a suggestion to use brackets.
22
+ class AssignTag < ::Liquid::Assign
23
+ THING = /(?:#{::Liquid::QuotedString}|[\w\-\[\]\.]+?)/o
24
+ SYNTAX = /\A\s*(#{::Liquid::VariableSignature}+?)((?:\[#{THING}\])*)\s*=\s*(.*)\s*\z/om
25
+ LOOKUP_SYNTAX = /\[(#{THING})\]/o
26
+
27
+ attr_reader :to_lookups
28
+
29
+ def initialize(tag_name, markup, parse_context)
30
+ # Liquid::Assign#initialize parses the target as a plain variable name, and
31
+ # in strict2 mode refuses a bracketed one, so its parser is skipped here.
32
+ ::Liquid::Tag.instance_method(:initialize).bind_call(self, tag_name, markup, parse_context)
33
+
34
+ match = SYNTAX.match(markup)
35
+ self.class.raise_syntax_error(parse_context) unless match
36
+
37
+ @to = match[1]
38
+
39
+ unless match[2].empty?
40
+ @to_lookups = match[2].scan(LOOKUP_SYNTAX).flatten
41
+
42
+ if @to_lookups.any? { |lookup| !lookup.match?(/\A#{::Liquid::QuotedString}\z/o) && lookup.match?(/[\[\]]/) }
43
+ raise(
44
+ ::Liquid::SyntaxError,
45
+ "Encountered nested bracket lookups during {% assign #{markup.strip} %}, but this is not permitted",
46
+ )
47
+ end
48
+ end
49
+
50
+ @from = ::Liquid::Variable.new(match[3], parse_context)
51
+ end
52
+
53
+ def render_to_output_buffer(context, output)
54
+ LightwardLiquidExt.assign_hook&.call(context)
55
+
56
+ if @to.split(".").size > 1
57
+ replacement_to = @to.gsub(/\.(\w+)/, '["\1"]')
58
+ replacement_markup = @markup.strip.sub(@to, replacement_to)
59
+ raise(
60
+ ::Liquid::Error,
61
+ "Assignment with dot lookups is not permitted; try replacing {% assign #{@markup.strip} %} with " \
62
+ "{% assign #{replacement_markup} %}",
63
+ )
64
+ end
65
+
66
+ if @to_lookups.nil?
67
+ val = copy_for_variable(@from.render(context))
68
+ context.scopes.last[@to] = val
69
+ owned_by(context)[val] = true if val.is_a?(Hash) || val.is_a?(Array)
70
+ else
71
+ thing = assignable_root(context)
72
+ lookup_representation = @to
73
+
74
+ @to_lookups[0..-2].each do |lookup|
75
+ lookup_representation += "[#{lookup}]"
76
+ lookup_value = context[lookup]
77
+
78
+ assert_lookupable!(thing, lookup_representation, lookup_value, lookup)
79
+ thing = thing[lookup_value]
80
+ assert_assignable!(thing, lookup_representation)
81
+ end
82
+
83
+ # The value lands inside as many hashes and arrays as there are lookups,
84
+ # so it gets that many fewer levels of its own.
85
+ val = Support.deep_copy(@from.render(context), levels: MAX_DEPTH - @to_lookups.size)
86
+
87
+ assign_in(thing, context[@to_lookups.last], val, context: context)
88
+ end
89
+
90
+ context.resource_limits.increment_assign_score(assign_score_of(val))
91
+
92
+ output
93
+ end
94
+
95
+ private
96
+
97
+ # The hash or array named by the target, ready to be changed in place.
98
+ #
99
+ # Only the outermost scope holds what {% assign %} made, and the hashes and
100
+ # arrays this context assigned are recorded as its own. Anything else found
101
+ # there (a `render` argument, say, which is the caller's object) is copied
102
+ # into place before the first change, so assignment never reaches back into
103
+ # whoever passed it.
104
+ def assignable_root(context)
105
+ outermost = context.scopes.last
106
+
107
+ # Liquid reads a name from the innermost scope that has it, so a loop
108
+ # variable or include parameter shadows an assigned variable of the same
109
+ # name. Refuse it rather than change the shadowed one.
110
+ if context.scopes[0..-2].any? { |scope| scope.key?(@to) }
111
+ raise(
112
+ ::Liquid::Error,
113
+ "Tried to assign within `#{@to}` during {% assign #{@markup.strip} %}, but `#{@to}` is a loop " \
114
+ "variable or an include parameter, which can't be assigned into. To perform this assignment, " \
115
+ "start by copying it into a variable of your own, e.g. {% assign my_#{@to} = #{@to} %}.",
116
+ )
117
+ end
118
+
119
+ unless outermost.key?(@to)
120
+ if context.environments.any? { |environment| environment.key?(@to) }
121
+ raise(
122
+ ::Liquid::Error,
123
+ "Tried to assign within an environment variable during {% assign #{@markup.strip} %}. " \
124
+ "To perform this assignment, start by overriding the environment variable with a " \
125
+ "new locally-defined hash or array.",
126
+ )
127
+ end
128
+ end
129
+
130
+ thing = outermost[@to]
131
+ owned = owned_by(context)
132
+ return thing if owned.key?(thing)
133
+
134
+ # Not ours, so it's copied before the first change, and the copy is a plain
135
+ # Hash or Array. That lets a Hash or Array subclass through here (one handed
136
+ # to a render partial, say); anything else is refused.
137
+ unless thing.is_a?(Hash) || thing.is_a?(Array)
138
+ assert_assignable!(thing, @to)
139
+ end
140
+
141
+ thing = Support.deep_copy(thing)
142
+ context.resource_limits.increment_assign_score(assign_score_of(thing))
143
+ outermost[@to] = thing
144
+ owned[thing] = true
145
+
146
+ thing
147
+ end
148
+
149
+ # The hashes and arrays this context's own assigns created. Held weakly, so a
150
+ # collection that's been overwritten can be collected, and compared by
151
+ # identity, since an equal hash someone else passed in isn't one of ours.
152
+ # (ObjectSpace::WeakMap rather than WeakKeyMap: WeakKeyMap compares keys by
153
+ # equality, and a hash's equality changes as it's assigned into.)
154
+ def owned_by(context)
155
+ context.instance_variable_get(:@lightward_liquid_ext_owned) ||
156
+ context.instance_variable_set(:@lightward_liquid_ext_owned, ObjectSpace::WeakMap.new)
157
+ end
158
+
159
+ # A plain `{% assign x = value %}` copies the keyword literals (they're frozen
160
+ # and shared, and an assigned `newline` must stop being the literal), and
161
+ # copies hashes and arrays all the way down, so assigning into `x` later can't
162
+ # reach back into `value`. Everything else is stored as is.
163
+ def copy_for_variable(value)
164
+ if KeywordLiterals.literal?(value) || value.is_a?(Hash) || value.is_a?(Array)
165
+ Support.deep_copy(value)
166
+ else
167
+ value
168
+ end
169
+ end
170
+
171
+ def assert_lookupable!(object, object_representation, lookup_value, lookup_representation)
172
+ addendum = (lookup_representation != lookup_value ? " (found #{Support.describe_key(lookup_value)})" : "")
173
+
174
+ case object
175
+ when Hash
176
+ unless lookup_value.is_a?(String)
177
+ raise(
178
+ ::Liquid::Error,
179
+ "Tried to resolve `#{object_representation}` during `{% assign #{@markup.strip} %}`, but " \
180
+ "`#{lookup_representation}` is not a string and cannot be used for hash lookups#{addendum}",
181
+ )
182
+ end
183
+ when Array
184
+ unless lookup_value.is_a?(Integer)
185
+ raise(
186
+ ::Liquid::Error,
187
+ "Tried to resolve `#{object_representation}` during `{% assign #{@markup.strip} %}`, but " \
188
+ "`#{lookup_representation}` is not an integer and cannot be used for array lookups#{addendum}",
189
+ )
190
+ end
191
+ end
192
+ end
193
+
194
+ def assign_in(object, key, value, context:)
195
+ case object
196
+ when Hash
197
+ unless key.is_a?(String)
198
+ raise(
199
+ ::Liquid::Error,
200
+ "Tried to use #{Support.describe_key(key)} as a key for hash assignment during " \
201
+ "{% assign #{@markup.strip} %}, but only strings can be used for hash assignment",
202
+ )
203
+ end
204
+
205
+ # The key costs what Liquid charges for a string; the value is charged
206
+ # with every assignment, after this.
207
+ context.resource_limits.increment_assign_score(assign_score_of(key))
208
+
209
+ object[key] = value
210
+ when Array
211
+ unless key.is_a?(Integer)
212
+ raise(
213
+ ::Liquid::Error,
214
+ "Tried to use #{Support.describe_key(key)} as an index for array assignment during " \
215
+ "{% assign #{@markup.strip} %}, but only integers can be used for array assignment",
216
+ )
217
+ end
218
+
219
+ if key < -object.length
220
+ raise(
221
+ ::Liquid::Error,
222
+ "Tried to use #{key} as an index for array assignment during {% assign #{@markup.strip} %}, " \
223
+ "but the array only has #{object.length} #{object.length == 1 ? "item" : "items"}",
224
+ )
225
+ end
226
+
227
+ # Ruby arrays aren't sparse: assigning far past the end fills every slot in
228
+ # between with nil. Cap those slots, and charge them to the assign score,
229
+ # before making them.
230
+ gap = key - object.length
231
+ max_gap = LightwardLiquidExt.max_array_gap
232
+ if max_gap && gap > max_gap
233
+ raise(
234
+ ::Liquid::Error,
235
+ "Tried to use #{key} as an index for array assignment during {% assign #{@markup.strip} %}, " \
236
+ "but that would add #{gap} empty slots to an array of #{object.length}, and at most " \
237
+ "#{max_gap} are allowed",
238
+ )
239
+ end
240
+ context.resource_limits.increment_assign_score(gap) if gap > 0
241
+
242
+ begin
243
+ object[key] = value
244
+ rescue IndexError, NoMemoryError
245
+ raise(
246
+ ::Liquid::Error,
247
+ "Tried to use #{key} as an index for array assignment during {% assign #{@markup.strip} %}, " \
248
+ "but that index is too large",
249
+ )
250
+ end
251
+ end
252
+ end
253
+
254
+ def assert_assignable!(thing, lookup_representation)
255
+ return if thing.instance_of?(Hash) || thing.instance_of?(Array)
256
+
257
+ raise(
258
+ ::Liquid::Error,
259
+ "Encountered a #{Support.type_name(thing)} at `#{lookup_representation}` that is not assignable, " \
260
+ "in `{% assign #{@markup.strip} %}`. Only locally-initialized hashes and arrays support assignments.",
261
+ )
262
+ end
263
+ end
264
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ module Filters
5
+ # push and unshift return a new array; the original is never changed.
6
+ module ArrayFilters
7
+ def push(object, *args)
8
+ ArrayFilters.copy_of_array("push", object).push(*args)
9
+ end
10
+
11
+ def unshift(object, *args)
12
+ ArrayFilters.copy_of_array("unshift", object).unshift(*args)
13
+ end
14
+
15
+ def self.copy_of_array(filter_name, object)
16
+ unless object.respond_to?(:to_ary)
17
+ raise(
18
+ ArgumentError,
19
+ "#{filter_name} can only be used on array-like objects; received #{Support.type_name(object)} instead",
20
+ )
21
+ end
22
+
23
+ # to_ary returns the array itself when given an array, so copy it.
24
+ object.to_ary.dup
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ module Filters
5
+ # json renders any value as JSON. parse_json reads a JSON string into hashes,
6
+ # arrays and plain values; with `silent: true`, invalid JSON gives nil instead
7
+ # of an error.
8
+ #
9
+ # An object can choose its own JSON form by responding to `as_liquid_json`.
10
+ module JsonFilters
11
+ # The walk below bounds what it visits, and the generator's own max_nesting
12
+ # bounds the rest, including whatever an as_liquid_json returns.
13
+ def json(object)
14
+ JSON.dump(JsonFilters.object_as_liquid_json(object), nil, nil, max_nesting: MAX_DEPTH)
15
+ rescue JSON::NestingError
16
+ Support.too_deep!
17
+ end
18
+
19
+ def parse_json(object, options = {})
20
+ unless object.is_a?(String)
21
+ raise(ArgumentError, "parse_json can only be used on strings; received #{Support.type_name(object)} instead")
22
+ end
23
+
24
+ JSON.parse(object)
25
+ rescue JSON::ParserError => error
26
+ return if options.is_a?(Hash) && Support.present?(options["silent"])
27
+
28
+ # The parser's own message quotes the input wherever parsing failed, which
29
+ # can be anywhere in it, so only its position is kept.
30
+ line = error.respond_to?(:line) ? error.line : nil
31
+ column = error.respond_to?(:column) ? error.column : nil
32
+ position = line && column ? " at line #{line}, column #{column}" : ""
33
+
34
+ # cause: nil, so the parser's error (and the input it quotes) doesn't ride
35
+ # along in the cause chain into a host's logs.
36
+ raise(ArgumentError, "parse_json failed: invalid JSON#{position}\n\ninput:\n#{Support.excerpt(object)}", cause: nil)
37
+ end
38
+
39
+ # Walks hashes and collections at most MAX_DEPTH deep (which also stops a
40
+ # cycle), raising a Liquid::Error past that.
41
+ def self.object_as_liquid_json(object, levels: MAX_DEPTH)
42
+ if object.respond_to?(:as_liquid_json)
43
+ object.as_liquid_json
44
+ elsif object.is_a?(Hash)
45
+ Support.too_deep! if levels < 1
46
+ object.transform_values { |value| object_as_liquid_json(value, levels: levels - 1) }
47
+ elsif object.respond_to?(:each)
48
+ Support.too_deep! if levels < 1
49
+ object.map { |value| object_as_liquid_json(value, levels: levels - 1) }
50
+ else
51
+ object
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ module Filters
5
+ # Liquid's split and replace, taught about the `newline` literal. Given
6
+ # `newline` itself, they match "\r\n" as well as "\n". Given anything else,
7
+ # they defer to Liquid's own filters unchanged. (Liquid's own newline_to_br
8
+ # already handles "\r\n", so it needs nothing from here.)
9
+ module NewlineFilters
10
+ LINEBREAK_PATTERN = /\r?\n/
11
+
12
+ def replace(input, string, replacement = "")
13
+ return super unless KeywordLiterals.newline?(string)
14
+
15
+ ::Liquid::Utils.to_s(input).gsub(LINEBREAK_PATTERN, ::Liquid::Utils.to_s(replacement))
16
+ end
17
+
18
+ def split(input, pattern)
19
+ return super unless KeywordLiterals.newline?(pattern)
20
+
21
+ ::Liquid::Utils.to_s(input).split(LINEBREAK_PATTERN)
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ module Filters
5
+ # match and scan, with Ruby-compatible regular expression patterns given as strings.
6
+ #
7
+ # Each match runs under LightwardLiquidExt.regexp_timeout (1 second unless the
8
+ # host changes it; nil inherits Ruby's global Regexp.timeout). Every match `scan` finds counts once against Liquid's
9
+ # render score, so render_score_limit bounds it.
10
+ module RegexpFilters
11
+ CACHE_SIZE = 100
12
+
13
+ @cache = {}
14
+ @cache_mutex = Mutex.new
15
+
16
+ # One match. It renders as the matched text, and behaves like it for `size`,
17
+ # `first` and `last` (the text's length, first character and last character)
18
+ # and for string filters. `captures` gives an array of the groups, and
19
+ # `named_captures` a hash.
20
+ #
21
+ # match[0] and match["name"] are deliberately not supported: Liquid treats
22
+ # match.foo and match["foo"] as the same lookup, so [] can't serve both
23
+ # captures and the text's own properties. Asking for the arrays by name
24
+ # keeps what's going on visible.
25
+ class MatchDrop < ::Liquid::Drop
26
+ def initialize(matchdata)
27
+ super()
28
+ @matchdata = matchdata
29
+ @matchdata_string = matchdata.to_s
30
+ end
31
+
32
+ def to_s
33
+ @matchdata_string
34
+ end
35
+
36
+ def captures
37
+ @matchdata.captures
38
+ end
39
+
40
+ def named_captures
41
+ @matchdata.named_captures
42
+ end
43
+
44
+ def size
45
+ @matchdata_string.size
46
+ end
47
+
48
+ def first
49
+ @matchdata_string[0]
50
+ end
51
+
52
+ def last
53
+ @matchdata_string[-1]
54
+ end
55
+ end
56
+
57
+ def match(input, pattern, _options = {})
58
+ regexp = RegexpFilters.build_regexp("match", input, pattern)
59
+
60
+ matchdata = RegexpFilters.timing_out("match", pattern, regexp) { regexp.match(input) }
61
+ MatchDrop.new(matchdata) if matchdata
62
+ end
63
+
64
+ def scan(input, pattern, _options = {})
65
+ regexp = RegexpFilters.build_regexp("scan", input, pattern)
66
+ resource_limits = @context&.resource_limits
67
+
68
+ RegexpFilters.timing_out("scan", pattern, regexp) do
69
+ input.to_enum(:scan, regexp).map do
70
+ resource_limits&.increment_render_score(1)
71
+ MatchDrop.new(Regexp.last_match)
72
+ end
73
+ end
74
+ end
75
+
76
+ class << self
77
+ def build_regexp(filter_name, input, pattern)
78
+ unless input.is_a?(String)
79
+ raise(
80
+ ArgumentError,
81
+ "#{filter_name} can only be used on a string; received #{Support.type_name(input)} instead",
82
+ )
83
+ end
84
+
85
+ unless pattern.is_a?(String)
86
+ raise(
87
+ ArgumentError,
88
+ "#{filter_name}'s first argument must be a Ruby-compatible regexp pattern string; " \
89
+ "received #{Support.type_name(pattern)} instead",
90
+ )
91
+ end
92
+
93
+ compile(pattern, LightwardLiquidExt.regexp_timeout)
94
+ rescue RegexpError => error
95
+ raise(
96
+ ArgumentError,
97
+ "Regular expression error in \"#{filter_name}\" filter for pattern " \
98
+ "#{Support.excerpt(pattern).to_json}: #{Support.excerpt(error.message, 200)}",
99
+ )
100
+ end
101
+
102
+ def timing_out(filter_name, pattern, regexp)
103
+ yield
104
+ rescue Regexp::TimeoutError
105
+ # The timeout the match actually ran under: the regexp's own, or, when
106
+ # it has none, Ruby's global one.
107
+ timeout = regexp.timeout || Regexp.timeout
108
+ raise(
109
+ ::Liquid::Error,
110
+ "#{filter_name} gave up on pattern #{Support.excerpt(pattern).to_json} after " \
111
+ "#{timeout} seconds; try a simpler pattern",
112
+ )
113
+ end
114
+
115
+ private
116
+
117
+ # Compiled patterns are kept, a few at a time, so a loop doesn't recompile.
118
+ def compile(pattern, timeout)
119
+ key = [pattern, timeout]
120
+
121
+ @cache_mutex.synchronize do
122
+ regexp = @cache.delete(key)
123
+ return @cache[key] = regexp if regexp
124
+ end
125
+
126
+ regexp = Regexp.new(pattern, timeout: timeout)
127
+
128
+ @cache_mutex.synchronize do
129
+ @cache.shift while @cache.size >= CACHE_SIZE
130
+ @cache[key] = regexp
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ # Adds three keyword literals to Liquid expressions, in environments that have
5
+ # had LightwardLiquidExt.install!:
6
+ #
7
+ # array an empty array
8
+ # hash an empty hash
9
+ # newline "\n"
10
+ #
11
+ # Like Liquid's own `true` or `nil`, these are literals, not variables:
12
+ # `{% assign hash = "x" %}` doesn't change what `hash` means afterwards, and a
13
+ # variable the host passes in under one of these names can't be read. Templates
14
+ # rendered in any other environment are untouched.
15
+ #
16
+ # The values are frozen and shared. The assign tag copies them on assignment, so
17
+ # every `{% assign x = array %}` gets an array of its own. `newline` is recognized
18
+ # by identity: the newline filters treat the literal itself specially, and any
19
+ # other "\n" (an assigned copy, a captured line break) as an ordinary string.
20
+ #
21
+ # Lookups rooted at a keyword resolve against the literal, whatever the host
22
+ # passed in under that name: `{{ array.size }}` is 0, `{{ hash.anything }}` and
23
+ # `{{ hash["anything"] }}` are empty, `{{ newline.size }}` is 1.
24
+ module KeywordLiterals
25
+ LITERALS = {
26
+ "hash" => {}.freeze,
27
+ "array" => [].freeze,
28
+ # String.new, so this is an object of its own. A frozen "\n" literal would be
29
+ # deduplicated by Ruby with every other frozen "\n" literal in the process,
30
+ # and a host's own "\n" would then pass for the keyword.
31
+ "newline" => String.new("\n").freeze,
32
+ }.freeze
33
+
34
+ NEWLINE = LITERALS.fetch("newline")
35
+
36
+ @environments = ObjectSpace::WeakMap.new
37
+ @mutex = Mutex.new
38
+
39
+ class << self
40
+ def literal?(value)
41
+ LITERALS.each_value.any? { |literal| value.equal?(literal) }
42
+ end
43
+
44
+ def newline?(value)
45
+ value.equal?(NEWLINE)
46
+ end
47
+
48
+ def installed?(environment)
49
+ !environment.nil? && @environments.key?(environment)
50
+ end
51
+
52
+ # The literal named by this markup, or nil, for an installed environment.
53
+ def lookup(environment, markup)
54
+ return unless markup.is_a?(String) && installed?(environment)
55
+
56
+ LITERALS[markup.strip]
57
+ end
58
+
59
+ def install!(environment)
60
+ @mutex.synchronize do
61
+ unless ::Liquid::ParseContext.ancestors.include?(ParseContextHooks)
62
+ check_compatibility!
63
+ ::Liquid::ParseContext.prepend(ParseContextHooks)
64
+ ::Liquid::Context.prepend(ContextHooks)
65
+ end
66
+
67
+ @environments[environment] = true
68
+ end
69
+ end
70
+
71
+ private
72
+
73
+ def check_compatibility!
74
+ version = Gem::Version.new(::Liquid::VERSION)
75
+ unless version >= Gem::Version.new("5.14") && version < Gem::Version.new("6")
76
+ incompatible!("supports Liquid >= 5.14 and < 6, and Liquid #{::Liquid::VERSION} is loaded")
77
+ end
78
+
79
+ expectations = {
80
+ [::Liquid::ParseContext, :parse_expression] => [[:req, :markup], [:key, :safe]],
81
+ [::Liquid::ParseContext, :safe_parse_expression] => [[:req, :parser]],
82
+ [::Liquid::Context, :[]] => [[:req, :expression]],
83
+ [::Liquid::Context, :find_variable] => [[:req, :key], [:key, :raise_on_not_found]],
84
+ }
85
+
86
+ expectations.each do |(klass, method_name), parameters|
87
+ found = klass.method_defined?(method_name) ? klass.instance_method(method_name).parameters : nil
88
+ next if found == parameters
89
+
90
+ incompatible!("expected #{klass}##{method_name} to take #{parameters.inspect}, and found #{found.inspect}")
91
+ end
92
+
93
+ unless ::Liquid::ParseContext.method_defined?(:environment) && ::Liquid::Context.method_defined?(:environment)
94
+ incompatible!("expected Liquid::ParseContext and Liquid::Context to know their environment")
95
+ end
96
+ end
97
+
98
+ def incompatible!(detail)
99
+ raise(IncompatibleLiquidError, "lightward_liquid_ext #{detail}. See #{README_URL}")
100
+ end
101
+ end
102
+
103
+ # Hands Liquid's own safe_parse_expression an expression it has already read.
104
+ ParsedExpression = Struct.new(:expression)
105
+
106
+ # Prepended to Liquid::ParseContext, which every tag and variable parses its
107
+ # expressions through. The literals return before Liquid's expression cache is
108
+ # consulted, so the cache never holds them.
109
+ module ParseContextHooks
110
+ def parse_expression(markup, safe: false)
111
+ return super if !safe && error_mode == :strict2 # let Liquid raise its own error
112
+
113
+ literal = KeywordLiterals.lookup(environment, markup)
114
+ literal.nil? ? super : literal
115
+ end
116
+
117
+ def safe_parse_expression(parser)
118
+ return super unless KeywordLiterals.installed?(environment)
119
+
120
+ expression = parser.expression
121
+ literal = KeywordLiterals.lookup(environment, expression)
122
+ literal.nil? ? super(ParsedExpression.new(expression)) : literal
123
+ end
124
+ end
125
+
126
+ # Prepended to Liquid::Context, for lookups made at render time (the assign
127
+ # tag's bracket lookups, and hosts calling context["..."]).
128
+ module ContextHooks
129
+ # Every variable lookup's root comes through here (VariableLookup, `self`,
130
+ # every parse mode), so a lookup rooted at a keyword name resolves against
131
+ # the literal and never reaches a host variable of that name.
132
+ def find_variable(key, raise_on_not_found: true)
133
+ return super unless key.is_a?(String) && KeywordLiterals.installed?(environment)
134
+
135
+ literal = LITERALS[key]
136
+ literal.nil? ? super : literal
137
+ end
138
+
139
+ def [](expression)
140
+ return super unless KeywordLiterals.installed?(environment)
141
+
142
+ case expression
143
+ when true, false, Numeric, Hash, Array
144
+ expression
145
+ when Symbol
146
+ self[expression.to_s]
147
+ when String, nil
148
+ literal = KeywordLiterals.lookup(environment, expression)
149
+ literal.nil? ? super : literal
150
+ else
151
+ raise(::Liquid::Error, "Liquid expression must be a string or primitive; got #{expression.class.name}")
152
+ end
153
+ end
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ # Small helpers, kept here so the gem needs nothing beyond liquid and json.
5
+ module Support
6
+ module_function
7
+
8
+ # A plain-words name for an object's type, for error messages:
9
+ # 5 => "integer", nil => "nil class", SomeModule::WidgetDrop.new => "widget drop".
10
+ def type_name(object)
11
+ name = object.class.name
12
+ return "object" if name.nil?
13
+
14
+ name
15
+ .split("::").last
16
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
17
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
18
+ .tr("_", " ")
19
+ .downcase
20
+ end
21
+
22
+ # Copies hashes, arrays and strings all the way down, so that nothing reachable
23
+ # from the copy is shared with the original. Other objects (numbers, drops,
24
+ # anything a host put in the context) are kept as they are: Liquid has no way
25
+ # to change them in place.
26
+ #
27
+ # Hashes and arrays come out as plain Hash and Array, built from their stored
28
+ # entries only. A hash's default value or default proc isn't carried over: it
29
+ # would be shared with the original, and a missing key should read as missing.
30
+ #
31
+ # Refuses anything nested deeper than `levels` hashes and arrays (which also
32
+ # stops a cycle), with a Liquid::Error rather than a stack overflow.
33
+ #
34
+ # The core classes' own methods do the walking, never a subclass's overrides, so a
35
+ # subclass whose `map`, `each_pair` or `dup` returns itself (or anything else) is
36
+ # still copied into a new plain Hash, Array or String.
37
+ HASH_EACH_PAIR = ::Hash.instance_method(:each_pair)
38
+ ARRAY_MAP = ::Array.instance_method(:map)
39
+ private_constant :HASH_EACH_PAIR, :ARRAY_MAP
40
+
41
+ def deep_copy(value, levels: MAX_DEPTH)
42
+ case value
43
+ when Hash
44
+ too_deep! if levels < 1
45
+ copy = {}
46
+ HASH_EACH_PAIR.bind_call(value) { |key, entry| copy[key] = deep_copy(entry, levels: levels - 1) }
47
+ copy
48
+ when Array
49
+ too_deep! if levels < 1
50
+ ARRAY_MAP.bind_call(value) { |entry| deep_copy(entry, levels: levels - 1) }
51
+ when String
52
+ String.new(value)
53
+ else
54
+ value
55
+ end
56
+ end
57
+
58
+ def too_deep!
59
+ raise(
60
+ ::Liquid::Error,
61
+ "Hashes and arrays can be nested at most #{MAX_DEPTH} levels deep, and this one would go deeper",
62
+ )
63
+ end
64
+
65
+ # The start of a long string, for quoting in an error message.
66
+ def excerpt(string, length = 80)
67
+ string = string.to_s
68
+ string.length > length ? "#{string[0, length]}…" : string
69
+ end
70
+
71
+ # JSON for the types JSON has; a description for anything else. Used to show
72
+ # a hash key or array index in an error message.
73
+ def describe_key(value)
74
+ case value
75
+ when String, Integer, Float, true, false, nil
76
+ value.to_json
77
+ else
78
+ "an instance of #{value.class.name.to_s.split("::").last}"
79
+ end
80
+ end
81
+
82
+ def present?(value)
83
+ return false if value.nil? || value == false
84
+ return !value.strip.empty? if value.is_a?(String)
85
+ return !value.empty? if value.respond_to?(:empty?)
86
+
87
+ true
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LightwardLiquidExt
4
+ VERSION = "1.0.0"
5
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "liquid"
5
+
6
+ require_relative "lightward_liquid_ext/version"
7
+ require_relative "lightward_liquid_ext/support"
8
+ require_relative "lightward_liquid_ext/keyword_literals"
9
+ require_relative "lightward_liquid_ext/assign_tag"
10
+ require_relative "lightward_liquid_ext/filters/newline_filters"
11
+ require_relative "lightward_liquid_ext/filters/regexp_filters"
12
+ require_relative "lightward_liquid_ext/filters/array_filters"
13
+ require_relative "lightward_liquid_ext/filters/json_filters"
14
+
15
+ # Liquid extensions extracted from Mechanic. Requiring this file changes nothing;
16
+ # call LightwardLiquidExt.install! to turn the extensions on.
17
+ module LightwardLiquidExt
18
+ README_URL = "https://github.com/lightward/liquid-ext#readme"
19
+
20
+ # How deep hashes and arrays may nest, when assigned or rendered as JSON. The
21
+ # same as the JSON library's default.
22
+ MAX_DEPTH = 100
23
+
24
+ # Raised on install when the loaded Liquid isn't one this gem knows how to extend.
25
+ class IncompatibleLiquidError < StandardError; end
26
+
27
+ FILTERS = [
28
+ Filters::NewlineFilters,
29
+ Filters::RegexpFilters,
30
+ Filters::ArrayFilters,
31
+ Filters::JsonFilters,
32
+ ].freeze
33
+
34
+ class << self
35
+ # Optional callable, given the Liquid::Context, run at the start of every
36
+ # {% assign %} render. nil by default. A host can use it to yield the thread,
37
+ # check for cancellation, or count work. Whatever it raises propagates.
38
+ attr_accessor :assign_hook
39
+
40
+ # Seconds a single regular expression match in `match` or `scan` may take
41
+ # before it gives up (Ruby's Regexp timeout). nil means inherit Ruby's
42
+ # process-wide Regexp.timeout, which is no limit unless the host sets one.
43
+ # This bounds one match, not a render: see the README on untrusted templates.
44
+ attr_accessor :regexp_timeout
45
+
46
+ # The most empty slots one array assignment may create past the end of an
47
+ # array (`{% assign a[1000000] = 1 %}` on an empty array creates 1,000,000).
48
+ # Checked before anything is allocated, whatever Liquid limits are set. nil
49
+ # for no cap.
50
+ attr_accessor :max_array_gap
51
+
52
+ # Registers the assign tag and the filters on the given environment, and turns
53
+ # on the keyword literals (array, hash, newline) for templates parsed and
54
+ # rendered in it. Other environments are untouched. Safe to call more than once.
55
+ def install!(environment = ::Liquid::Environment.default)
56
+ # Tag and filters first: if the environment refuses them (a built, frozen
57
+ # one, say), it's left as it was, keywords included.
58
+ environment.register_tag("assign", AssignTag)
59
+ FILTERS.each { |filter| environment.register_filter(filter) }
60
+
61
+ KeywordLiterals.install!(environment)
62
+
63
+ environment
64
+ end
65
+ end
66
+
67
+ self.regexp_timeout = 1.0
68
+ self.max_array_gap = 100_000
69
+ end
metadata ADDED
@@ -0,0 +1,103 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lightward_liquid_ext
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Lightward
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: base64
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: json
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '2.0'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '2.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: liquid
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '5.14'
47
+ - - "<"
48
+ - !ruby/object:Gem::Version
49
+ version: '6'
50
+ type: :runtime
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '5.14'
57
+ - - "<"
58
+ - !ruby/object:Gem::Version
59
+ version: '6'
60
+ description: 'Liquid extensions that have run in Mechanic (mechanic.dev) for years:
61
+ the keyword literals array, hash and newline; assign into hashes and arrays by key
62
+ or index; split and replace that understand newline; match and scan with regular
63
+ expressions; push and unshift; json and parse_json.'
64
+ executables: []
65
+ extensions: []
66
+ extra_rdoc_files: []
67
+ files:
68
+ - README.md
69
+ - UNLICENSE
70
+ - lib/lightward_liquid_ext.rb
71
+ - lib/lightward_liquid_ext/assign_tag.rb
72
+ - lib/lightward_liquid_ext/filters/array_filters.rb
73
+ - lib/lightward_liquid_ext/filters/json_filters.rb
74
+ - lib/lightward_liquid_ext/filters/newline_filters.rb
75
+ - lib/lightward_liquid_ext/filters/regexp_filters.rb
76
+ - lib/lightward_liquid_ext/keyword_literals.rb
77
+ - lib/lightward_liquid_ext/support.rb
78
+ - lib/lightward_liquid_ext/version.rb
79
+ homepage: https://github.com/lightward/liquid-ext
80
+ licenses:
81
+ - Unlicense
82
+ metadata:
83
+ homepage_uri: https://github.com/lightward/liquid-ext
84
+ rubygems_mfa_required: 'true'
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '3.4'
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubygems_version: 4.0.20
100
+ specification_version: 4
101
+ summary: Array and hash literals, assignment into hashes and arrays, and a few filters,
102
+ for Shopify's Liquid.
103
+ test_files: []