hamster-web 0.1.0.pre.2 → 0.1.0.pre.5

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.
Files changed (83) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -0
  3. data/README.md +576 -5
  4. data/lib/hamster/agent_guidance.rb +56 -0
  5. data/lib/hamster/application_graph.rb +336 -0
  6. data/lib/hamster/build/assets.rb +72 -0
  7. data/lib/hamster/build/callbacks.rb +124 -0
  8. data/lib/hamster/build/jobs.rb +78 -0
  9. data/lib/hamster/build/manifest.rb +31 -9
  10. data/lib/hamster/build/query_accessors.rb +18 -0
  11. data/lib/hamster/check.rb +122 -0
  12. data/lib/hamster/cli.rb +105 -12
  13. data/lib/hamster/data/persistence.rb +11 -6
  14. data/lib/hamster/data/read/nodes.rb +2 -0
  15. data/lib/hamster/data/read/schema.rb +28 -16
  16. data/lib/hamster/data/read/validator.rb +3 -0
  17. data/lib/hamster/data/record.rb +15 -1
  18. data/lib/hamster/data/table.rb +22 -3
  19. data/lib/hamster/database/database.rb +2 -25
  20. data/lib/hamster/database/migrator.rb +151 -0
  21. data/lib/hamster/database/pool.rb +7 -3
  22. data/lib/hamster/database/result.rb +3 -3
  23. data/lib/hamster/dev.rb +116 -0
  24. data/lib/hamster/endpoint_generator.rb +7 -0
  25. data/lib/hamster/form.rb +110 -0
  26. data/lib/hamster/generators/plan.rb +96 -0
  27. data/lib/hamster/generators/runner.rb +168 -0
  28. data/lib/hamster/jobs/adapters.rb +106 -0
  29. data/lib/hamster/jobs/postgres_queue.rb +146 -0
  30. data/lib/hamster/jobs/worker.rb +103 -0
  31. data/lib/hamster/jobs.rb +116 -0
  32. data/lib/hamster/migration.rb +36 -0
  33. data/lib/hamster/native_smoke.rb +53 -0
  34. data/lib/hamster/schema_validation.rb +4 -2
  35. data/lib/hamster/storage/disk.rb +89 -0
  36. data/lib/hamster/storage.rb +152 -0
  37. data/lib/hamster/test_database.rb +63 -0
  38. data/lib/hamster/test_runner.rb +29 -0
  39. data/lib/hamster/testing.rb +110 -0
  40. data/lib/hamster/web/action/base.rb +49 -4
  41. data/lib/hamster/web/application.rb +9 -0
  42. data/lib/hamster/web/assets.rb +28 -0
  43. data/lib/hamster/web/context.rb +122 -1
  44. data/lib/hamster/web/files.rb +118 -0
  45. data/lib/hamster/web/http.rb +4 -2
  46. data/lib/hamster/web/json.rb +39 -0
  47. data/lib/hamster/web/multipart.rb +138 -0
  48. data/lib/hamster/web/router.rb +13 -2
  49. data/lib/hamster/web/routing/base.rb +4 -2
  50. data/lib/hamster/web/turbo.rb +24 -0
  51. data/lib/hamster/web/version.rb +1 -1
  52. data/lib/hamster/web/view/form.rb +18 -1
  53. data/lib/hamster/web.rb +9 -0
  54. data/templates/app/.agents/skills/hamster-database/SKILL.md +29 -0
  55. data/templates/app/.agents/skills/hamster-endpoint/SKILL.md +27 -0
  56. data/templates/app/.dockerignore +19 -0
  57. data/templates/app/AGENTS.md +20 -7
  58. data/templates/app/Dockerfile +77 -0
  59. data/templates/app/Gemfile +5 -1
  60. data/templates/app/README.md +365 -2
  61. data/templates/app/app/application.rb +15 -0
  62. data/templates/app/app/assets/application.css +2 -0
  63. data/templates/app/app/assets/application.js +2 -0
  64. data/templates/app/app/assets/controllers/hello_controller.js +5 -0
  65. data/templates/app/app/assets/vendor/VERSIONS.md +12 -0
  66. data/templates/app/app/assets/vendor/stimulus.LICENSE.txt +9 -0
  67. data/templates/app/app/assets/vendor/stimulus.js +2563 -0
  68. data/templates/app/app/assets/vendor/turbo.LICENSE.txt +20 -0
  69. data/templates/app/app/assets/vendor/turbo.js +7178 -0
  70. data/templates/app/app/routes/mappings.rb +1 -0
  71. data/templates/app/app/routes/up/index/action.rb +14 -0
  72. data/templates/app/app/views/layouts/application.html.erb +2 -1
  73. data/templates/app/bin/hamster +8 -0
  74. data/templates/app/bin/server +13 -1
  75. data/templates/app/bin/worker +24 -0
  76. data/templates/app/config/application.rb +1 -1
  77. data/templates/app/config/deploy.worker.yml.example +32 -0
  78. data/templates/app/public/.keep +0 -0
  79. data/templates/app/test/home_test.rb +8 -0
  80. data/templates/app/test/native_http.rb +11 -0
  81. data/templates/app/test/native_server.rb +10 -0
  82. data/templates/app/test/test_helper.rb +8 -0
  83. metadata +58 -4
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+ module Hamster
3
+ module CompiledAssets
4
+ def self.paths; {}; end
5
+ def self.types; {}; end
6
+ end
7
+ module Assets
8
+ module_function
9
+ def path(name)
10
+ value = CompiledAssets.paths[name.to_s]
11
+ raise ArgumentError, "Unknown asset #{name}" unless value
12
+ value.to_s
13
+ end
14
+ def response(env)
15
+ path = env.fetch("PATH_INFO", "/")
16
+ return nil unless path.start_with?("/assets/")
17
+ type = CompiledAssets.types[path]
18
+ return Http.response(404, "Asset not found") unless type
19
+ return Http.response(405, "Method not allowed", {"allow" => "GET, HEAD"}) unless %w[GET HEAD].include?(env.fetch("REQUEST_METHOD", "GET"))
20
+ directory = File.join(ENV.fetch("HAMSTER_APP_ROOT", Dir.pwd), "public/assets")
21
+ result = Downloads.file(path.delete_prefix("/assets/"), root: directory, content_type: type, disposition: "inline")
22
+ result[1]["cache-control"] = "public, max-age=31536000, immutable"
23
+ result
24
+ rescue Errno::ENOENT, Errno::ENOTDIR
25
+ Http.response(404, "Asset not found")
26
+ end
27
+ end
28
+ end
@@ -14,7 +14,128 @@ module Hamster
14
14
  end
15
15
 
16
16
  def form
17
- @form ||= Http.parse_parameters(env.fetch("rack.input").read.to_s)
17
+ claim_body!(:form)
18
+ if multipart?
19
+ parse_multipart.fields
20
+ else
21
+ @form ||= Http.parse_parameters(env.fetch("rack.input").read.to_s)
22
+ end
23
+ end
24
+
25
+ def claim_body!(kind)
26
+ if @body_kind && @body_kind != kind
27
+ raise RequestBodyError.new(400, "Request body was already parsed in another format")
28
+ end
29
+ @body_kind = kind
30
+ end
31
+
32
+ def json
33
+ claim_body!(:json)
34
+ return @json if @json_parsed
35
+ media = env.fetch("CONTENT_TYPE", "").split(";", 2).first.to_s.strip.downcase
36
+ unless media == "application/json" || media.match?(%r{\Aapplication/[a-z0-9!#$&^_.+-]+\+json\z})
37
+ raise RequestBodyError.new(415, "Expected an application/json request body")
38
+ end
39
+ maximum = env.fetch("hamster.json_max_bytes", 1048576)
40
+ raise ArgumentError, "JSON body limit must be a positive integer" unless maximum.is_a?(Integer) && maximum > 0
41
+ bytes = +""
42
+ input = env.fetch("rack.input")
43
+ while (chunk = input.read([65536, maximum + 1 - bytes.bytesize].min))
44
+ break if chunk.empty?
45
+ bytes << chunk
46
+ raise RequestBodyError.new(413, "JSON request body is too large") if bytes.bytesize > maximum
47
+ end
48
+ bytes.force_encoding("UTF-8")
49
+ raise RequestBodyError.new(400, "JSON request body must be UTF-8") unless bytes.valid_encoding?
50
+ begin
51
+ @json = JSON.parse(bytes)
52
+ JSONValue.normalize(@json)
53
+ rescue StandardError
54
+ raise RequestBodyError.new(400, "Malformed or unsupported JSON request body")
55
+ end
56
+ @json_parsed = true
57
+ @json
58
+ end
59
+
60
+ # Explicit negotiation: callers choose their JSON/HTML/Turbo response branch.
61
+ # Most-specific media ranges override wildcards, including q=0 exclusions.
62
+ def format
63
+ @negotiated = true
64
+ accept = env.fetch("HTTP_ACCEPT", "").to_s
65
+ return :html if accept.strip.empty?
66
+ candidates = [[:html, "text/html"], [:json, "application/json"], [:turbo_stream, "text/vnd.turbo-stream.html"]]
67
+ winner, best, best_specificity, best_index = :none, 0.0, -1, 1000000
68
+ candidates.each do |kind, mime|
69
+ specificity, quality, first_index = -1, 0.0, 1000000
70
+ accept.split(",").each_with_index do |range, range_index|
71
+ parts = range.strip.downcase.split(";").map(&:strip)
72
+ media = parts.shift
73
+ score = media == mime ? 2 : (media == mime.split("/").first + "/*" ? 1 : (media == "*/*" ? 0 : -1))
74
+ next if score < 0
75
+ q = 1.0
76
+ parts.each do |part|
77
+ if part.start_with?("q=")
78
+ value = part.delete_prefix("q=")
79
+ q = value.match?(/\A(?:0(?:\.[0-9]{0,3})?|1(?:\.0{0,3})?)\z/) ? value.to_f : 0.0
80
+ end
81
+ end
82
+ if score > specificity || (score == specificity && q > quality)
83
+ specificity, quality, first_index = score, q, range_index
84
+ end
85
+ end
86
+ if quality > 0 && (quality > best || (quality == best && (specificity > best_specificity || (specificity == best_specificity && first_index < best_index))))
87
+ winner, best, best_specificity, best_index = kind, quality, specificity, first_index
88
+ end
89
+ end
90
+ winner
91
+ end
92
+
93
+ def turbo_frame
94
+ value = env.fetch("HTTP_TURBO_FRAME", "")
95
+ value.empty? ? nil : Turbo.identifier(value)
96
+ end
97
+
98
+ def wants_json?
99
+ format == :json
100
+ end
101
+
102
+ def response_headers(headers)
103
+ return headers unless @negotiated
104
+ result = headers.dup
105
+ vary = result.fetch("vary", "").split(",").map(&:strip).reject(&:empty?)
106
+ result["vary"] = (vary + ["Accept", "Turbo-Frame"]).uniq.join(", ")
107
+ result
108
+ end
109
+
110
+ def multipart?
111
+ env.fetch("CONTENT_TYPE", "").downcase.start_with?("multipart/")
112
+ end
113
+
114
+ def parse_multipart
115
+ claim_body!(:form)
116
+ @multipart ||= Multipart.new(env.fetch("rack.input"), env.fetch("CONTENT_TYPE"), env.fetch("hamster.upload_options", {})).parse
117
+ end
118
+
119
+ def uploads
120
+ multipart? ? parse_multipart.uploads : {}
121
+ end
122
+
123
+ def finish_response(response)
124
+ response[2] = RequestBody.new(response[2], self) if @multipart && !@multipart.uploads.empty?
125
+ response
126
+ end
127
+
128
+ def close_uploads
129
+ @multipart.close if @multipart
130
+ end
131
+
132
+ def valid_csrf?(expected)
133
+ return false if expected.to_s.empty? || !same_origin?
134
+ supplied = env["HTTP_X_CSRF_TOKEN"] || form["csrf_token"]
135
+ return false unless supplied.is_a?(String) && supplied.bytesize == expected.to_s.bytesize
136
+ difference = 0
137
+ expected.to_s.bytes.each_with_index { |byte, index| difference |= byte ^ supplied.getbyte(index) }
138
+ difference == 0
18
139
  end
19
140
 
20
141
  def same_origin?
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+ module Hamster
3
+ class RequestBodyError < StandardError
4
+ attr_reader :status
5
+ def initialize(status, message)
6
+ @status = status
7
+ super(message)
8
+ end
9
+ end
10
+
11
+ class UploadedFile
12
+ attr_reader :filename, :content_type, :size, :io
13
+ def initialize(filename, content_type, directory)
14
+ @filename, @content_type, @size = filename, content_type, 0
15
+ @path = File.join(directory, "hamster-#{Process.pid}-#{rand(1_000_000_000)}.upload")
16
+ @io = File.open(@path, File::RDWR | File::CREAT | File::EXCL, 0600)
17
+ @io.binmode
18
+ @closed = false
19
+ end
20
+ def append(bytes)
21
+ @io.write(bytes)
22
+ @size += bytes.bytesize
23
+ end
24
+ def finish
25
+ @io.flush
26
+ @io.rewind
27
+ end
28
+ def copy_to(destination)
29
+ @io.rewind
30
+ File.open(destination, File::WRONLY | File::CREAT | File::EXCL, 0600) do |target|
31
+ while (chunk = @io.read(65536))
32
+ target.write(chunk)
33
+ end
34
+ end
35
+ @io.rewind
36
+ destination
37
+ end
38
+ def close
39
+ return if @closed
40
+ @closed = true
41
+ begin
42
+ @io.close unless @io.closed?
43
+ ensure
44
+ File.unlink(@path) if File.exist?(@path)
45
+ end
46
+ end
47
+ end
48
+
49
+ class FileBody
50
+ def initialize(io, owned = true)
51
+ @io, @owned, @closed = io, owned, false
52
+ end
53
+ def each
54
+ while (chunk = @io.read(65536))
55
+ yield chunk.b
56
+ end
57
+ end
58
+ def close
59
+ return if @closed
60
+ @closed = true
61
+ @io.close if @owned && !@io.closed?
62
+ end
63
+ end
64
+
65
+ class RequestBody
66
+ def initialize(body, context)
67
+ @body, @context, @closed = body, context, false
68
+ end
69
+ def each
70
+ @body.each { |chunk| yield chunk }
71
+ end
72
+ def close
73
+ return if @closed
74
+ @closed = true
75
+ begin
76
+ @body.close if @body.respond_to?(:close)
77
+ ensure
78
+ @context.close_uploads
79
+ end
80
+ end
81
+ end
82
+
83
+ module Downloads
84
+ module_function
85
+ def headers(filename, content_type, disposition)
86
+ raise ArgumentError, "invalid disposition" unless %w[attachment inline].include?(disposition)
87
+ raise ArgumentError, "invalid content type" unless content_type.match?(%r{\A[a-zA-Z0-9!\#$&^_.+-]+/[a-zA-Z0-9!\#$&^_.+-]+\z})
88
+ name = filename.to_s
89
+ raise ArgumentError, "invalid filename" if name.empty? || name.match?(/[\x00-\x1f\x7f\\\/]/) || !name.valid_encoding?
90
+ ascii = name.gsub(/[^a-zA-Z0-9._-]/, "_")
91
+ encoded = name.bytes.map { |b| ((b >= 65 && b <= 90) || (b >= 97 && b <= 122) || (b >= 48 && b <= 57) || [45,46,95].include?(b)) ? b.chr : "%#{b.to_s(16).upcase.rjust(2, '0')}" }.join
92
+ {"content-type" => content_type, "content-disposition" => "#{disposition}; filename=\"#{ascii}\"; filename*=UTF-8''#{encoded}", "x-content-type-options" => "nosniff", "cache-control" => "no-store"}
93
+ end
94
+
95
+ def file(path, root:, filename: nil, content_type: "application/octet-stream", disposition: "attachment")
96
+ root_path = File.realpath(root)
97
+ absolute = File.expand_path(path, root_path)
98
+ raise ArgumentError, "file outside download root" unless absolute.start_with?(root_path + File::SEPARATOR)
99
+ cursor = File::SEPARATOR
100
+ absolute.split(File::SEPARATOR).reject(&:empty?).each do |part|
101
+ cursor = File.join(cursor, part)
102
+ raise ArgumentError, "symlink download path" if File.symlink?(cursor)
103
+ end
104
+ before = File.stat(absolute)
105
+ raise ArgumentError, "download must be a regular file" unless before.file?
106
+ result_headers = headers(filename || File.basename(absolute), content_type, disposition)
107
+ io = File.open(absolute, "rb")
108
+ begin
109
+ after = io.stat
110
+ raise ArgumentError, "download path changed" unless after.file? && before.ino == after.ino && before.dev == after.dev && File.realpath(absolute) == absolute
111
+ [200, result_headers, FileBody.new(io)]
112
+ rescue StandardError
113
+ io.close
114
+ raise
115
+ end
116
+ end
117
+ end
118
+ end
@@ -2,15 +2,17 @@
2
2
 
3
3
  module Hamster
4
4
  module Http
5
- MIME = {html: "text/html; charset=utf-8", turbo: "text/html; charset=utf-8",
5
+ MIME = {json: "application/json; charset=utf-8", html: "text/html; charset=utf-8", turbo: "text/html; charset=utf-8",
6
6
  turbo_stream: "text/vnd.turbo-stream.html; charset=utf-8"}.freeze
7
7
  module_function
8
8
 
9
9
  def parse_parameters(encoded)
10
- encoded.split("&").each_with_object({}) do |part, values|
10
+ values = {}
11
+ encoded.split("&").each do |part|
11
12
  key, value = part.split("=", 2)
12
13
  values[decode(key)] = decode(value.to_s)
13
14
  end
15
+ values
14
16
  end
15
17
 
16
18
  def decode(value)
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+ require "json"
3
+
4
+ module Hamster
5
+ module JSONValue
6
+ module_function
7
+ # Normalize only explicit JSON values; never call record/object serializers.
8
+ def normalize(value, depth = 0)
9
+ raise ArgumentError, "JSON nesting exceeds 64 levels" if depth > 64
10
+ case value
11
+ when NilClass, TrueClass, FalseClass, Integer
12
+ value
13
+ when Float
14
+ raise ArgumentError, "JSON numbers must be finite" unless value.finite?
15
+ value
16
+ when String
17
+ raise ArgumentError, "JSON strings must be UTF-8" unless value.dup.force_encoding("UTF-8").valid_encoding?
18
+ value
19
+ when Array
20
+ value.map { |item| normalize(item, depth + 1) }
21
+ when Hash
22
+ result = {}
23
+ value.each do |key, item|
24
+ raise ArgumentError, "JSON keys must be strings or symbols" unless key.is_a?(String) || key.is_a?(Symbol)
25
+ name = key.to_s
26
+ raise ArgumentError, "Duplicate JSON key #{name}" if result.key?(name)
27
+ normalize(name, depth + 1)
28
+ result[name] = normalize(item, depth + 1)
29
+ end
30
+ result
31
+ else
32
+ raise ArgumentError, "Unsupported JSON value #{value.class}; select fields explicitly"
33
+ end
34
+ end
35
+ def generate(value)
36
+ JSON.generate(normalize(value))
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,138 @@
1
+ # frozen_string_literal: true
2
+ module Hamster
3
+ class Multipart
4
+ attr_reader :fields, :uploads
5
+ def initialize(input, content_type, options = {})
6
+ # Spinel 10f112c51 can leave mutable header payloads in regex registers
7
+ # that another worker's GC does not root. Match owned header copies.
8
+ match = content_type.dup.match(/\Amultipart\/form-data\s*;\s*boundary=(?:"([^"\r\n]+)"|([^;\s]+))\s*\z/i)
9
+ boundary = match && (match[1] || match[2])
10
+ fail_body(400, "invalid multipart boundary") unless boundary && boundary.bytesize <= 70 && boundary.match?(/\A[ -~]+\z/)
11
+ @input, @buffer, @total = input, "".b, 0
12
+ @maximum = options.fetch(:max_body_bytes, 1048576)
13
+ @parts = options.fetch(:max_parts, 128)
14
+ @header_limit = options.fetch(:max_part_header_bytes, 16384)
15
+ @field_limit = options.fetch(:max_field_bytes, 65536)
16
+ @file_limit = options.fetch(:max_file_bytes, @maximum)
17
+ @directory = options.fetch(:upload_directory, ENV.fetch("TMPDIR", "/tmp"))
18
+ [@maximum, @parts, @header_limit, @field_limit, @file_limit].each do |limit|
19
+ raise ArgumentError, "multipart limits must be positive integers" unless limit.is_a?(Integer) && limit > 0
20
+ end
21
+ @fields, @uploads, @all = {}, {}, []
22
+ @boundary = boundary.b
23
+ end
24
+ def fail_body(status, message)
25
+ raise RequestBodyError.new(status, message)
26
+ end
27
+ def read_more
28
+ chunk = @input.read(16384)
29
+ fail_body(400, "truncated multipart body") if chunk.nil? || chunk.empty?
30
+ @total += chunk.bytesize
31
+ fail_body(413, "multipart body too large") if @total > @maximum
32
+ @buffer << chunk.b
33
+ end
34
+ def take_until(marker, limit)
35
+ loop do
36
+ position = @buffer.index(marker)
37
+ if position
38
+ fail_body(413, "multipart section too large") if position > limit
39
+ value = @buffer.byteslice(0, position)
40
+ @buffer = @buffer.byteslice(position + marker.bytesize, @buffer.bytesize) || "".b
41
+ return value
42
+ end
43
+ fail_body(413, "multipart section too large") if @buffer.bytesize > limit + marker.bytesize
44
+ read_more
45
+ end
46
+ end
47
+ def parse
48
+ read_more while @buffer.bytesize < @boundary.bytesize + 4
49
+ prefix = "--#{@boundary}\r\n".b
50
+ fail_body(400, "invalid multipart opening") unless @buffer.start_with?(prefix)
51
+ @buffer = @buffer.byteslice(prefix.bytesize, @buffer.bytesize) || "".b
52
+ count = 0
53
+ loop do
54
+ count += 1
55
+ fail_body(413, "too many multipart parts") if count > @parts
56
+ raw = take_until("\r\n\r\n".b, @header_limit)
57
+ headers = {}
58
+ raw.split("\r\n").each do |line|
59
+ key, value = line.split(":", 2)
60
+ fail_body(400, "invalid multipart header") unless value && key.match?(/\A[a-zA-Z0-9-]+\z/) && !headers.key?(key.downcase)
61
+ headers[key.downcase] = value.strip
62
+ end
63
+ disposition = headers.fetch("content-disposition", "")
64
+ match = disposition.dup.match(/\Aform-data;\s*name="([^"\r\n\x00]+)"(?:;\s*filename="([^"\r\n\x00]*)")?\z/)
65
+ fail_body(400, "invalid multipart disposition") unless match
66
+ name, filename = match[1], match[2]
67
+ upload = nil
68
+ value = "".b
69
+ unless filename.nil?
70
+ filename = filename.dup.force_encoding("UTF-8")
71
+ fail_body(400, "unsafe upload filename") if filename.match?(/[\\\/\x00-\x1f\x7f]/) || !filename.valid_encoding? || [".", ".."].include?(filename)
72
+ content_type = headers.fetch("content-type", "application/octet-stream")
73
+ fail_body(400, "invalid upload content type") unless content_type.match?(%r{\A[a-zA-Z0-9!\#$&^_.+-]+/[a-zA-Z0-9!\#$&^_.+-]+\z})
74
+ upload = UploadedFile.new(filename, content_type, @directory)
75
+ @all << upload
76
+ end
77
+ marker = "\r\n--#{@boundary}".b
78
+ loop do
79
+ position = @buffer.index(marker)
80
+ if position
81
+ read_more while @buffer.bytesize < position + marker.bytesize + 2
82
+ suffix = @buffer.byteslice(position + marker.bytesize, 2)
83
+ if suffix == "--" || suffix == "\r\n"
84
+ emit(@buffer.byteslice(0, position), upload, value)
85
+ @buffer = @buffer.byteslice(position + marker.bytesize, @buffer.bytesize) || "".b
86
+ break
87
+ end
88
+ # A boundary-like sequence within binary data is ordinary content.
89
+ emit(@buffer.byteslice(0, position + 2), upload, value)
90
+ @buffer = @buffer.byteslice(position + 2, @buffer.bytesize) || "".b
91
+ elsif @buffer.bytesize > marker.bytesize + 2
92
+ length = @buffer.bytesize - marker.bytesize - 2
93
+ emit(@buffer.byteslice(0, length), upload, value)
94
+ @buffer = @buffer.byteslice(length, @buffer.bytesize) || "".b
95
+ else
96
+ read_more
97
+ end
98
+ end
99
+ if upload
100
+ upload.finish
101
+ (@uploads[name] ||= []) << upload
102
+ else
103
+ value.force_encoding("UTF-8")
104
+ fail_body(400, "invalid multipart text encoding") unless value.valid_encoding?
105
+ (@fields[name] ||= []) << value
106
+ end
107
+ ending = @buffer.byteslice(0, 2)
108
+ @buffer = @buffer.byteslice(2, @buffer.bytesize) || "".b
109
+ if ending == "--"
110
+ while (tail = @input.read(16384)) && !tail.empty?
111
+ @total += tail.bytesize
112
+ fail_body(413, "multipart body too large") if @total > @maximum
113
+ @buffer << tail.b
114
+ fail_body(400, "invalid multipart ending") if @buffer.bytesize > 2
115
+ end
116
+ fail_body(400, "invalid multipart ending") unless @buffer.empty? || @buffer == "\r\n"
117
+ break
118
+ end
119
+ end
120
+ self
121
+ rescue StandardError
122
+ close
123
+ raise
124
+ end
125
+ def emit(bytes, upload, value)
126
+ if upload
127
+ fail_body(413, "uploaded file too large") if upload.size + bytes.bytesize > @file_limit
128
+ upload.append(bytes)
129
+ else
130
+ fail_body(413, "multipart field too large") if value.bytesize + bytes.bytesize > @field_limit
131
+ value << bytes
132
+ end
133
+ end
134
+ def close
135
+ @all.each(&:close)
136
+ end
137
+ end
138
+ end
@@ -12,7 +12,13 @@ module Hamster
12
12
  def call(env, connection = nil)
13
13
  method = env.fetch("REQUEST_METHOD", "GET").upcase
14
14
  path = env.fetch("PATH_INFO", "/")
15
+ context = Context.new(env, connection)
16
+ if method == "POST" && env.fetch("CONTENT_TYPE", "").split(";", 2).first == "application/x-www-form-urlencoded"
17
+ override = context.form["_method"]
18
+ method = override if ["PATCH", "DELETE"].include?(override)
19
+ end
15
20
  route = @routes.find { |candidate| candidate.match(method, path) }
21
+ route ||= @routes.find { |candidate| candidate.match("GET", path) } if method == "HEAD"
16
22
  unless route
17
23
  allowed = @routes.select { |candidate| candidate.match(method, path, method_only: true) }
18
24
  return Http.response(:method_not_allowed, METHOD_NOT_ALLOWED,
@@ -20,8 +26,13 @@ module Hamster
20
26
  return Http.response(:not_found, NOT_FOUND)
21
27
  end
22
28
 
23
- env["route_params"] = route.match(method, path)
24
- route.action.new(Context.new(env, connection)).call
29
+ env["route_params"] = route.match(method == "HEAD" && route.method == "GET" ? "GET" : method, path)
30
+ begin
31
+ context.finish_response(route.action.new(context).dispatch)
32
+ rescue StandardError
33
+ context.close_uploads
34
+ raise
35
+ end
25
36
  end
26
37
  end
27
38
  end
@@ -7,7 +7,8 @@ module Hamster
7
7
 
8
8
  def initialize(name, method, pattern, action)
9
9
  @name, @method, @pattern, @action = name, method, pattern, action
10
- @segments = pattern.split("/").reject(&:empty?)
10
+ @segments = []
11
+ pattern.split("/").each { |segment| @segments << segment.to_s unless segment.to_s.empty? }
11
12
  end
12
13
 
13
14
  def match(request_method, path, method_only: false)
@@ -60,7 +61,7 @@ module Hamster
60
61
  end
61
62
 
62
63
  class Base
63
- SUPPORTED_METHODS = %w[GET POST PATCH DELETE].freeze
64
+ SUPPORTED_METHODS = %w[GET HEAD POST PATCH DELETE].freeze
64
65
  CONVENTIONAL_ACTIONS = {"New" => "new", "Edit" => "edit", "Create" => "create", "Update" => "update", "Destroy" => "destroy"}.freeze
65
66
 
66
67
  def self.routes
@@ -68,6 +69,7 @@ module Hamster
68
69
  end
69
70
 
70
71
  def self.get(path, to:, as: nil); add_route("GET", path, to, as); end
72
+ def self.head(path, to:, as: nil); add_route("HEAD", path, to, as); end
71
73
  def self.post(path, to:, as: nil); add_route("POST", path, to, as); end
72
74
  def self.patch(path, to:, as: nil); add_route("PATCH", path, to, as); end
73
75
  def self.delete(path, to:, as: nil); add_route("DELETE", path, to, as); end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+ module Hamster
3
+ module Turbo
4
+ ACTIONS = %w[replace append prepend remove update].freeze
5
+ module_function
6
+ def identifier(value)
7
+ id = value.to_s
8
+ raise ArgumentError, "invalid Turbo DOM id" unless id.match?(/\A[a-zA-Z][a-zA-Z0-9_:.-]*\z/)
9
+ id
10
+ end
11
+ def frame(id, content, attributes = {})
12
+ raise ArgumentError, "frame attributes cannot override id" if attributes.keys.any? { |key| key.to_s == "id" }
13
+ HTML.tag("turbo-frame", content, attributes.merge(id: identifier(id)))
14
+ end
15
+ def stream(action, target, content = nil)
16
+ raise ArgumentError, "unsupported Turbo stream action" unless ACTIONS.include?(action.to_s)
17
+ raise ArgumentError, "remove does not accept content" if action.to_s == "remove" && !content.nil?
18
+ template = action.to_s == "remove" ? nil : HTML.tag("template", content)
19
+ # action here is a validated Turbo verb, whereas HTML's action attribute
20
+ # is a URL. Keep the generic helper's URL validation intact.
21
+ HTML.raw_reviewed("<turbo-stream action=\"#{action}\" target=\"#{identifier(target)}\">#{template}</turbo-stream>")
22
+ end
23
+ end
24
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Hamster
4
4
  module Web
5
- VERSION = "0.1.0.pre.2"
5
+ VERSION = "0.1.0.pre.5"
6
6
  end
7
7
  end
@@ -77,6 +77,22 @@ module Hamster
77
77
  HTML.tag(:p, message, id: "#{field_id(name)}-error", class: "error", role: "alert")
78
78
  end
79
79
 
80
+ def label(name, text = nil, attributes = {})
81
+ raise ArgumentError, "label attributes cannot override for" if attributes.keys.any? { |key| key.to_s == "for" }
82
+ HTML.tag(:label, text || name.to_s.tr("_", " ").capitalize, attributes.merge(for: field_id(name)))
83
+ end
84
+
85
+ def error_summary
86
+ entries = @errors.flat_map do |name, messages|
87
+ Array(messages).map { |message| HTML.tag(:li, "#{name}: #{message}") }
88
+ end
89
+ entries.empty? ? HTML.join([]) : HTML.tag(:div, HTML.tag(:ul, HTML.join(entries)), role: "alert", class: "errors")
90
+ end
91
+
92
+ def finish
93
+ HTML.raw_reviewed("</form>")
94
+ end
95
+
80
96
  def field_id(name)
81
97
  base = field_name(name).tr("_", "-")
82
98
  @namespace ? "#{@namespace}-#{base}" : base
@@ -108,7 +124,8 @@ module Hamster
108
124
  end
109
125
 
110
126
  def error_for(name)
111
- @errors.key?(name.to_sym) ? @errors[name.to_sym] : @errors[name.to_s]
127
+ value = @errors.key?(name.to_sym) ? @errors[name.to_sym] : @errors[name.to_s]
128
+ value.is_a?(Array) ? value.join("; ") : value
112
129
  end
113
130
 
114
131
  def reject_value_attribute!(attributes)
data/lib/hamster/web.rb CHANGED
@@ -5,9 +5,18 @@ require_relative "web/instrumentation"
5
5
  require_relative "web/routing/base"
6
6
  require_relative "web/view"
7
7
  require_relative "web/html"
8
+ require_relative "web/turbo"
8
9
  require_relative "web/view/form"
10
+ require_relative "web/json"
9
11
  require_relative "web/http"
10
12
  require_relative "web/action/base"
13
+ require_relative "web/files"
14
+ require_relative "web/assets"
15
+ require_relative "web/multipart"
11
16
  require_relative "web/context"
12
17
  require_relative "web/router"
13
18
  require_relative "web/application"
19
+
20
+ require_relative "form"
21
+
22
+ require_relative "jobs"
@@ -0,0 +1,29 @@
1
+ ---
2
+ name: hamster-database
3
+ description: Add and inspect Hamster SQL or Ruby migrations and validate model schema contracts. Use for this application's PostgreSQL schema lifecycle, not endpoint scaffolding.
4
+ ---
5
+
6
+ Read project AGENTS.md and database configuration. Identify the actual target
7
+ database before running commands; obtain explicit authorization before any
8
+ production mutation. Never print credentials into logs or reports.
9
+
10
+ - Inspect `bin/hamster db:migrate:status` and
11
+ `bin/hamster db:migrate:history --json`. `legacy_unknown` preserves historical
12
+ tracking without claiming a checksum was recorded. Missing or modified applied
13
+ files require investigation; do not bypass integrity checks or rewrite history.
14
+ - Add a chronological, unique `db/migrations/VERSION_name.rb` defining one
15
+ `Hamster::Migration` subclass with explicit `up` and `down`. Inspect current
16
+ framework documentation for supported DSL operations. Keep existing SQL files
17
+ intact; SQL migrations remain forward-only. Model declarations are a separate
18
+ schema contract, never an automatic migration source.
19
+ - On a disposable development/test database, run `bin/hamster db:migrate`, verify
20
+ schema/data behavior, run `bin/hamster db:rollback STEP=1`, then migrate again.
21
+ Rollback refuses batches containing an irreversible migration before writing.
22
+ - Run `bin/hamster db:validate` to check declarations against the selected schema,
23
+ plus documented project tests and native build verification when runtime
24
+ declarations change. Do not assume `db:validate` runs migrations.
25
+ - `bin/hamster db:structure:dump` explicitly writes a derived schema snapshot and
26
+ requires pg_dump. Do not use structure.sql as a second source of truth.
27
+
28
+ Migration Ruby executes in CRuby tooling. Do not import it into application code
29
+ or add transaction-control SQL inside a migration's framework-owned transaction.