@pulse-compute/provider-fastly 0.0.0 → 1.0.0-beta.10

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 (103) hide show
  1. package/README.md +53 -1
  2. package/dist/config-schema.json +103 -0
  3. package/dist/index.d.ts +77 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +67 -0
  6. package/dist/index.js.map +1 -0
  7. package/package.json +88 -5
  8. package/src/build/canonical-target.js +469 -0
  9. package/src/build/digest-native.js +25 -0
  10. package/src/build/effect-invocations.js +49 -0
  11. package/src/build/embedded-assets.as.ts +32 -0
  12. package/src/build/entities-native.js +559 -0
  13. package/src/build/fixed-memory-runtime.as.ts +148 -0
  14. package/src/build/kv-native.as.ts +331 -0
  15. package/src/build/kv-native.js +27 -0
  16. package/src/build/native-application-errors.js +159 -0
  17. package/src/build/native-binary-resources.js +30 -0
  18. package/src/build/native-body-forwarding.as.ts +341 -0
  19. package/src/build/native-body-forwarding.js +69 -0
  20. package/src/build/native-dynamic-backends.as.ts +115 -0
  21. package/src/build/native-dynamic-backends.js +52 -0
  22. package/src/build/native-fetch-deadlines.as.ts +164 -0
  23. package/src/build/native-fetch-deadlines.js +27 -0
  24. package/src/build/native-fetch-errors.js +38 -0
  25. package/src/build/native-handle-ownership.js +127 -0
  26. package/src/build/native-header-lookup.js +50 -0
  27. package/src/build/native-http-effects.js +994 -0
  28. package/src/build/native-http-shell.js +703 -0
  29. package/src/build/native-platform-capabilities.js +2654 -0
  30. package/src/build/native-request-body.js +44 -0
  31. package/src/build/native-request-headers.js +93 -0
  32. package/src/build/native-send-error-detail.as.ts +12 -0
  33. package/src/build/native-stdio.js +45 -0
  34. package/src/build/native-string-values.js +143 -0
  35. package/src/build/native-transport-details.as.ts +84 -0
  36. package/src/build/native-value-budget.js +90 -0
  37. package/src/build/package-native-application.js +114 -0
  38. package/src/build/request-budget.as.ts +50 -0
  39. package/src/build/request-budget.js +47 -0
  40. package/src/build/s3-body.as.ts +97 -0
  41. package/src/build/s3-native.as.ts +228 -0
  42. package/src/build/s3-native.js +30 -0
  43. package/src/build/schema-admission.js +83 -0
  44. package/src/build/schema-nested-json.js +93 -0
  45. package/src/build/schema-scalar-record.js +41 -0
  46. package/src/build/time-native.js +49 -0
  47. package/src/build/wasm-budget.js +28 -0
  48. package/src/compiler/assets-package-out-parity-proof.js +338 -0
  49. package/src/compiler/assets-provider-proof.js +499 -0
  50. package/src/compiler/config-provider-resolution.js +573 -0
  51. package/src/compiler/fastly-adapter.js +564 -0
  52. package/src/compiler/fastly-command-entry.js +390 -0
  53. package/src/compiler/fastly-config-secret-serve.js +323 -0
  54. package/src/compiler/fastly-hostcall-binding.js +598 -0
  55. package/src/compiler/fastly-readiness.js +477 -0
  56. package/src/compiler/index.js +40 -0
  57. package/src/compiler/lifecycle-parity-contract.js +70 -0
  58. package/src/compiler/lifecycle-parity-proof.js +260 -0
  59. package/src/compiler/route-handler-effect-proof.js +255 -0
  60. package/src/compiler/runtime-provider-kv.js +237 -0
  61. package/src/compiler/runtime-provider-shape.js +109 -0
  62. package/src/config-api.js +69 -0
  63. package/src/config-schema.d.ts +13 -0
  64. package/src/config-schema.js +27 -0
  65. package/src/config-schema.json +103 -0
  66. package/src/index.js +3 -0
  67. package/src/index.ts +143 -0
  68. package/src/javascript/assets-adapter.js +122 -0
  69. package/src/javascript/bindings-adapter.js +237 -0
  70. package/src/javascript/errors.js +26 -0
  71. package/src/javascript/fetch-adapter.js +93 -0
  72. package/src/javascript/grip-broadcast.js +261 -0
  73. package/src/javascript/jwt-verifier.js +147 -0
  74. package/src/javascript/lifecycle.js +55 -0
  75. package/src/javascript/local-loader.js +138 -0
  76. package/src/javascript/logging.js +35 -0
  77. package/src/javascript/package-effects.js +71 -0
  78. package/src/javascript/runtime-host.js +112 -0
  79. package/src/javascript/sha256.js +128 -0
  80. package/src/javascript/source-package.js +778 -0
  81. package/src/javascript/support.js +142 -0
  82. package/src/javascript/target-support-policy.js +277 -0
  83. package/src/javascript/target.js +89 -0
  84. package/src/javascript/test-runtime.js +408 -0
  85. package/src/provider-contract.js +88 -0
  86. package/src/runtime/assets-provider.js +464 -0
  87. package/src/runtime/canonical-api-runtime.js +603 -0
  88. package/src/runtime/index.js +28 -0
  89. package/src/runtime/provider-primitives-contract.js +272 -0
  90. package/src/runtime/provider-primitives.js +82 -0
  91. package/src/runtime/route-handler-effects.js +507 -0
  92. package/src/testing/conditional-kv-host.js +155 -0
  93. package/src/testing/fastly-cli.js +538 -0
  94. package/src/testing/native-dynamic-backends-host.js +39 -0
  95. package/src/testing/native-http-effects-host.js +398 -0
  96. package/src/testing/native-http-shell-host.js +190 -0
  97. package/src/testing/native-platform-capabilities-host.js +924 -0
  98. package/src/toolchain/body-forwarding.js +25 -0
  99. package/src/toolchain/config.js +144 -0
  100. package/src/toolchain/index.js +386 -0
  101. package/src/toolchain/logging.js +18 -0
  102. package/src/toolchain/native-execution.js +78 -0
  103. package/src/toolchain/s3.js +26 -0
@@ -0,0 +1,159 @@
1
+ 'use strict';
2
+
3
+ function enabled(plan) {
4
+ return (plan.routing?.entries || []).some(entry => entry.kind === 'error');
5
+ }
6
+
7
+ // Fetch-only applications also drain failed groups before their terminal response.
8
+ function settlementEnabled(plan) {
9
+ return enabled(plan) || (!plan.packages?.application && (plan.effects || []).some(effect => effect.kind === 'fetch'));
10
+ }
11
+
12
+ // Capture provider diagnostics before clearing them. A failed continuation is
13
+ // drained once; only an admitted application error can enter the next Router lane.
14
+ function runtimeSource(plan) {
15
+ const jwt = ['TOKEN_REQUIRED', 'BEARER_INVALID', 'MALFORMED', 'LIMIT_EXCEEDED',
16
+ 'ALGORITHM_NOT_ALLOWED', 'KEY_INVALID', 'SIGNATURE_INVALID', 'CLOCK_INVALID',
17
+ 'CLAIMS_INVALID', 'CLAIMS_SCHEMA_INVALID'];
18
+ return `
19
+ let __pulse_application_schema: i32 = 0
20
+ let __pulse_application_failed_schema: i32 = 0
21
+ function __pulse_application_code(): string {
22
+ if (__pulse_fastly_last_error == PULSE_ERROR_TRANSPORT && __pulse_fetch_failed()) return __pulse_fastly_error_stage == 271 ? "PULSE_FETCH_TIMEOUT" : "PULSE_FETCH_NETWORK"
23
+ if (__pulse_fastly_last_error == PULSE_ERROR_REQUEST_BODY)
24
+ return __pulse_fastly_error_stage == 21 ? "PULSE_BODY_TOO_LARGE" : "PULSE_REQUEST_BODY_INVALID_UTF8"
25
+ if (__pulse_fastly_jwt_error > 0) {
26
+ if (__pulse_fastly_last_error != PULSE_ERROR_JWT
27
+ && !(__pulse_fastly_last_error == PULSE_ERROR_SCHEMA && __pulse_fastly_jwt_error == 10)) return ""
28
+ switch (__pulse_fastly_jwt_error) {
29
+ ${jwt.map((code, i) => ` case ${i + 1}: return "PULSE_JWT_${code}"`).join('\n')}
30
+ default: return ""
31
+ }
32
+ }
33
+ if (__pulse_application_failed_schema == 0) return ""
34
+ if (__pulse_fastly_last_error == PULSE_ERROR_JSON) return "PULSE_SCHEMA_JSON_MALFORMED"
35
+ if (__pulse_fastly_last_error != PULSE_ERROR_SCHEMA) return ""
36
+ if (__pulse_fastly_error_stage == 21) return "PULSE_BODY_TOO_LARGE"
37
+ if (__pulse_fastly_error_stage == 44) return "PULSE_SCHEMA_CONTENT_TYPE"
38
+ // Stages 56/57 reject ScalarRecord and bounded nested JSON data.
39
+ // Stage 55 remains a fatal schema-ID/configuration error.
40
+ if ((__pulse_fastly_error_stage >= 50 && __pulse_fastly_error_stage <= 54)
41
+ || __pulse_fastly_error_stage == 56 || __pulse_fastly_error_stage == 57)
42
+ return __pulse_application_failed_schema == 2 ? "PULSE_SCHEMA_ENCODE" : "PULSE_SCHEMA_DECODE"
43
+ return ""
44
+ }
45
+ function __pulse_application_clear(): void {
46
+ __pulse_fastly_last_error = 0; __pulse_fastly_error_stage = 0; __pulse_fastly_error_effect = -1
47
+ __pulse_fastly_jwt_error = 0; __pulse_application_failed_schema = 0; __pulse_transport_error = null
48
+ }
49
+ ${(plan?.effects || []).length > 0 ? settlementSource(plan) : ''}
50
+ function host_router_error_take(): i32 {
51
+ if (__pulse_fastly_last_error == 0) return 0
52
+ const code = __pulse_application_code()
53
+ if (code.length == 0) return -1
54
+ // Never abandon a dispatched sibling to run application recovery.
55
+ for (let i = 0; i < PULSE_FASTLY_EFFECT_COUNT; i += 1)
56
+ if (unchecked(__pulse_fastly_pending_mode[i]) != PULSE_FASTLY_PENDING_NONE) return 0
57
+ const transport = __pulse_transport_error
58
+ __pulse_application_clear()
59
+ const error = host_value_object()
60
+ host_value_object_set(error, __pulse_fastly_string_value("code"), __pulse_fastly_string_value(code))
61
+ host_value_object_set(error, __pulse_fastly_string_value("name"), __pulse_fastly_string_value("PulseApplicationError"))
62
+ host_value_object_set(error, __pulse_fastly_string_value("message"), __pulse_fastly_string_value(code == "PULSE_FETCH_TIMEOUT" ? "Fetch header deadline exceeded." : code == "PULSE_FETCH_NETWORK" ? "Fetch transport failed." : "Pulse application data validation failed."))
63
+ if (transport != null) host_value_object_set(error, __pulse_fastly_string_value('detail'), __pulse_transport_value(transport))
64
+ return error
65
+ }
66
+ `;
67
+ }
68
+
69
+ // The caller retains the static pending-slot guards. The shared body owns one
70
+ // site's resolution and authenticated settlement; diagnostics carry the saved
71
+ // failure between calls without allocating an accumulator or merging slot state.
72
+ function settlementSource(plan) {
73
+ return `
74
+ // Returns 0 for recoverable/no failure, 1 for fatal, -1 for rejected settlement.
75
+ function __pulse_application_settle_effect(index: i32, fatal: bool): i32 {
76
+ let failure = __pulse_fastly_last_error
77
+ let stage = __pulse_fastly_error_stage
78
+ let effect = __pulse_fastly_error_effect
79
+ let jwt = __pulse_fastly_jwt_error
80
+ let schema = __pulse_application_failed_schema
81
+ let transport = __pulse_transport_error
82
+ const invocation = unchecked(__pulse_invocation_tickets[index])
83
+ __pulse_application_clear()
84
+ let result = host_value_undefined()
85
+ if (unchecked(__pulse_fastly_pending_mode[index]) != PULSE_FASTLY_PENDING_NONE) {
86
+ result = __pulse_fastly_resolve_effect(index)
87
+ if (result <= 0 && __pulse_fastly_last_error == 0) __pulse_fastly_fail(PULSE_ERROR_STATE, 101, index)
88
+ } else if (failure == 0) __pulse_fastly_fail(PULSE_ERROR_STATE, 101, index)
89
+ if (__pulse_fastly_last_error != 0) {
90
+ const terminal = ${enabled(plan) ? '__pulse_application_code().length == 0' : 'true'}
91
+ if (failure == 0 || (!fatal && terminal)) {
92
+ failure = __pulse_fastly_last_error; stage = __pulse_fastly_error_stage; effect = __pulse_fastly_error_effect
93
+ jwt = __pulse_fastly_jwt_error; schema = __pulse_application_failed_schema; transport = __pulse_transport_error; fatal = terminal
94
+ }
95
+ __pulse_application_clear()
96
+ result = host_value_undefined()
97
+ }
98
+ if (__pulse_invocation_settle(index, invocation, result) != 1) {
99
+ __pulse_fastly_fail(PULSE_ERROR_STATE, 101, index); __pulse_fastly_jwt_send_error(); return -1
100
+ }
101
+ __pulse_fastly_last_error = failure; __pulse_fastly_error_stage = stage; __pulse_fastly_error_effect = effect
102
+ __pulse_fastly_jwt_error = jwt; __pulse_application_failed_schema = schema; __pulse_transport_error = transport
103
+ return fatal ? 1 : 0
104
+ }
105
+ `;
106
+ }
107
+
108
+ // Fatal settlement uses the same response hook as synchronous failure; its
109
+ // instrumentation preserves deadline and transport-specific precedence.
110
+ function driverLoop(plan) {
111
+ return ` while (runStatus == 1) {
112
+ let fatal = __pulse_fastly_last_error != 0${enabled(plan) ? ' && __pulse_application_code().length == 0' : ''}
113
+ ${(plan.effects || []).map((_, index) => ` if (__pulse_effect_pending_${index} != 0) {
114
+ const settled = __pulse_application_settle_effect(${index}, fatal)
115
+ if (settled < 0) return
116
+ fatal = settled != 0
117
+ }`).join('\n')}
118
+ if (fatal) { __pulse_fastly_jwt_send_error(); return }
119
+ runStatus = pulse_resume()
120
+ }`;
121
+ }
122
+
123
+ function instrument(source) {
124
+ // The input is compiler-owned AS with simple, typed host signatures. Keep
125
+ // failure suppression on all imports so a failed expression has no effects.
126
+ source = source.replace(/function (host_\w+)\(([^)]*)\): (i32|void) \{/g,
127
+ (declaration, name, _args, result) => name === 'host_router_error_take' ? declaration
128
+ : `${declaration} if (__pulse_fastly_last_error != 0) return${result === 'void' ? '' : ['host_resource_check', 'host_workspace_check'].includes(name) ? ' -1' : ' 0'};`);
129
+ const wrappers = [
130
+ ['host_request_json', 'schema: i32', 'schema', '1'],
131
+ ['host_schema_decode', 'text: i32, schema: i32', 'text, schema', '1'],
132
+ ['host_schema_encode', 'value: i32, schema: i32', 'value, schema', '2'],
133
+ ['host_fetch_json', 'responseHandle: i32, schemaHandle: i32', 'responseHandle, schemaHandle', '1'],
134
+ ['host_response_json', 'value: i32, options: i32', 'value, options', '2'],
135
+ ['__pulse_fastly_schema_apply', 'schemaId: string, valueHandle: i32, encode: bool', 'schemaId, valueHandle, encode', 'encode ? 2 : 1']
136
+ ];
137
+ for (let [name, params, args, mode] of wrappers) {
138
+ if (name === '__pulse_fastly_schema_apply') {
139
+ // Text-result specialization adds an optional parameter. Preserve the
140
+ // compiler-owned declaration (including defaults) and forward every value.
141
+ const declaration = source.match(/function __pulse_fastly_schema_apply\(([^)]*)\): i32 \{/);
142
+ if (declaration) {
143
+ params = declaration[1];
144
+ args = params.split(',').map(parameter => parameter.split(':')[0].trim()).join(', ');
145
+ }
146
+ }
147
+ source = source.replace(`function ${name}(`, `function __pulse_application_impl_${name}(`);
148
+ source += `\nfunction ${name}(${params}): i32 {
149
+ const previous = __pulse_application_schema; __pulse_application_schema = ${mode}
150
+ const result = __pulse_application_impl_${name}(${args})
151
+ __pulse_application_schema = previous
152
+ return result
153
+ }\n`;
154
+ }
155
+ source = source.replace('__pulse_fastly_last_error = code;', '__pulse_application_failed_schema = __pulse_application_schema; __pulse_fastly_last_error = code;');
156
+ return source;
157
+ }
158
+
159
+ module.exports = Object.freeze({ enabled, settlementEnabled, runtimeSource, driverLoop, instrument });
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+ function source() { return `function __pulse_resource_request_check(): bool { return true }
3
+ function host_workspace_number_value(handle: i32): f64 {
4
+ if (__pulse_fastly_last_error != 0) return NaN;
5
+ const value = __pulse_fastly_value(handle);
6
+ if (value.kind != PULSE_VALUE_NUMBER) { __pulse_fastly_fail(PULSE_ERROR_VALUE, 280, -1); return NaN; }
7
+ return value.number;
8
+ }
9
+ function host_workspace_check(offset: f64, capacity: i32, value: f64): i32 {
10
+ if (__pulse_fastly_last_error != 0 || !__pulse_resource_request_check()) return -1;
11
+ if (!isFinite(offset) || Math.floor(offset) != offset || offset < 0 || offset >= capacity || capacity < 1 || capacity > 1024 || !isFinite(value)) {
12
+ __pulse_fastly_fail(PULSE_ERROR_VALUE, 280, -1); return -1;
13
+ }
14
+ return <i32>offset;
15
+ }
16
+ function host_resource_offset_value(handle: i32): f64 {
17
+ if (__pulse_fastly_last_error != 0) return NaN;
18
+ const value = __pulse_fastly_value(handle);
19
+ if (value.kind != PULSE_VALUE_NUMBER) { __pulse_fastly_fail(PULSE_ERROR_VALUE, 270, -1); return NaN; }
20
+ return value.number;
21
+ }
22
+ function host_resource_check(offset: f64, length: i32, width: i32): i32 {
23
+ if (__pulse_fastly_last_error != 0 || !__pulse_resource_request_check()) return -1;
24
+ if (!isFinite(offset) || offset < 0 || Math.floor(offset) != offset || length < 0 || width < 0 || offset > <f64>length || <f64>width > <f64>length - offset) {
25
+ __pulse_fastly_fail(PULSE_ERROR_VALUE, 270, -1); return -1;
26
+ }
27
+ return <i32>offset;
28
+ }
29
+ `; }
30
+ module.exports = { source };
@@ -0,0 +1,341 @@
1
+ // FWD9-02: sequential upload/response pumps. Payload bytes never become Pulse
2
+ // values. Fixed scratch and ABI outputs are reused, including the clock slot.
3
+ // close accepts EOF into Fastly; it is not a delivery/drain receipt.
4
+ @external('fastly_http_req', 'send_async_streaming')
5
+ declare function __fwd_dispatch(request: i32, body: i32, backend: usize, length: i32, pending: usize): i32
6
+ @external('fastly_http_body', 'abandon') declare function __fwd_abandon(body: i32): i32
7
+ @external('fastly_async_io', 'is_ready') declare function __fwd_ready(handle: i32, ready: usize): i32
8
+ @external('fastly_http_resp', 'header_names_get')
9
+ declare function __fwd_names(handle: i32, buffer: usize, size: i32, cursor: i32, end: usize, written: usize): i32
10
+ @external('fastly_http_resp', 'header_values_get')
11
+ declare function __fwd_values(handle: i32, name: usize, length: i32, buffer: usize, size: i32, cursor: i32, end: usize, written: usize): i32
12
+ const __fwd_buffer: usize = memory.data(16384)
13
+ const __fwd_headers: usize = memory.data(16384)
14
+ const __fwd_pairs: usize = memory.data(1024) // 64 x (name ptr/size, value ptr/size)
15
+ const __fwd_io: usize = memory.data(128) // aligned reusable ABI outputs
16
+ const __fwd_detail: usize = __fwd_io + 8
17
+ const __fwd_done: usize = __fwd_detail + __PULSE_SEND_ERROR_DETAIL_BYTES
18
+ const __fwd_response_out: usize = __fwd_done + 4
19
+ const __fwd_body_out: usize = __fwd_response_out + 4 // ends at +40; next scratch field starts there
20
+ let __fwd_source: i32 = -1
21
+ let __fwd_upload: i32 = -1
22
+ let __fwd_request: i32 = -1
23
+ let __fwd_pending: i32 = -1
24
+ let __fwd_response: i32 = -1
25
+ let __fwd_body: i32 = -1
26
+ let __fwd_downstream: i32 = -1
27
+ let __fwd_output: i32 = -1
28
+ let __fwd_index: i32 = -1
29
+ let __fwd_result: i32 = 0
30
+ let __fwd_marker: i32 = 0
31
+ let __fwd_failure: i32 = 0
32
+ let __fwd_committed: bool = false
33
+ let __fwd_reserved: bool = false
34
+ let __fwd_header_count: i32 = 0
35
+ let __fwd_request_length: i32 = -1
36
+ let __fwd_response_length: i32 = -1
37
+ let __fwd_status: i32 = 200
38
+ function host_request_body(): i32 {
39
+ if (__fwd_marker != 0 || __fwd_reserved) { __fwd_fail(400); return 0; }
40
+ const marker = new __PulseFastlyValue(); marker.kind = 90;
41
+ __fwd_marker = __pulse_fastly_put(marker); return __fwd_marker;
42
+ }
43
+ function __fwd_fail(status: i32): void {
44
+ if (__fwd_failure == 0) __fwd_failure = status;
45
+ __pulse_fastly_fail(PULSE_ERROR_HOSTCALL, 280, __fwd_index);
46
+ }
47
+ function __fwd_remaining(): i32 {
48
+ if (__fwd_failure != 0) return 0;
49
+ if (wasi_snapshot_preview1_clock_time_get(1, 1, __fwd_io) != 0) { __fwd_fail(504); return 0; }
50
+ const now = load<i64>(__fwd_io);
51
+ if (now < 0 || now < __request_last_clock || now < __pulse_fetch_last_clock) { __fwd_fail(504); return 0; }
52
+ __request_last_clock = now; __pulse_fetch_last_clock = now;
53
+ let remaining = f64(__request_deadline - now) / 1000000.0;
54
+ if (__request_expired || remaining <= 0) { __request_expired = true; __fwd_fail(504); return 0; }
55
+ if (__fwd_index >= 0) remaining = Math.min(remaining, __pulse_fetch_remaining(__fwd_index, now));
56
+ if (remaining <= 0) { __fwd_fail(504); return 0; }
57
+ return i32(Math.ceil(remaining)); // 1..30000; zero never reaches async.select
58
+ }
59
+ function __fwd_cleanup(): void {
60
+ if (__fwd_source >= 0) { __pulse_fetch_close_body(__fwd_source); __fwd_source = -1; }
61
+ if (__fwd_upload >= 0) { __fwd_abandon(__fwd_upload); __fwd_upload = -1; }
62
+ if (__fwd_request >= 0) { __pulse_fetch_close_request(__fwd_request); __fwd_request = -1; }
63
+ if (__fwd_body >= 0) { __pulse_fetch_close_body(__fwd_body); __fwd_body = -1; }
64
+ if (__fwd_response >= 0) { __pulse_fetch_close_response(__fwd_response); __fwd_response = -1; }
65
+ if (__fwd_output >= 0) { __pulse_fetch_close_response(__fwd_output); __fwd_output = -1; }
66
+ if (__fwd_downstream >= 0) { __fwd_abandon(__fwd_downstream); __fwd_downstream = -1; }
67
+ if (__fwd_pending >= 0) {
68
+ // No pending-request cancel ABI. Poll once without waiting and discard any
69
+ // late handles; an unresolved host operation ends at invocation teardown.
70
+ __pulse_send_error_detail_reset(__fwd_detail);
71
+ store<i32>(__fwd_done, 0);
72
+ const status = __pulse_fetch_poll(__fwd_pending, __fwd_detail, __fwd_done, __fwd_response_out, __fwd_body_out);
73
+ if (status == 0 && load<i32>(__fwd_done) == 1) {
74
+ __pulse_fetch_close_response(load<i32>(__fwd_response_out)); __pulse_fetch_close_body(load<i32>(__fwd_body_out));
75
+ }
76
+ __fwd_pending = -1;
77
+ }
78
+ }
79
+ function __fwd_error_response(): bool {
80
+ if (__fwd_committed) { __fwd_cleanup(); return true; }
81
+ if (__fwd_failure == 0) return false;
82
+ const status = __fwd_failure;
83
+ __fwd_cleanup(); __request_error_response = true;
84
+ __pulse_fastly_last_error = 0;
85
+ const value = new __PulseFastlyValue(); value.kind = PULSE_VALUE_RESPONSE; value.status = status;
86
+ value.text = status == 413 ? 'Payload Too Large' : status == 504 ? 'Gateway Timeout' : status == 400 ? 'Bad Request' : 'Bad Gateway';
87
+ __fwd_committed = true;
88
+ __pulse_fastly_send_result(__pulse_fastly_put(value)); return true;
89
+ }
90
+ function __fwd_lower(byte: u8): u8 { return byte >= 65 && byte <= 90 ? byte + 32 : byte; }
91
+ function __fwd_equal(ptr: usize, size: i32, text: string): bool {
92
+ if (size != text.length) return false;
93
+ for (let i = 0; i < size; i++) if (__fwd_lower(load<u8>(ptr + i)) != text.charCodeAt(i)) return false;
94
+ return true;
95
+ }
96
+ function __fwd_token(byte: u8): bool {
97
+ return (byte >= 48 && byte <= 57) || (byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122)
98
+ || byte == 33 || byte == 35 || byte == 36 || byte == 37 || byte == 38 || byte == 39 || byte == 42
99
+ || byte == 43 || byte == 45 || byte == 46 || byte == 94 || byte == 95 || byte == 96 || byte == 124 || byte == 126;
100
+ }
101
+ function __fwd_hop(ptr: usize, size: i32): bool {
102
+ return __fwd_equal(ptr,size,'connection') || __fwd_equal(ptr,size,'keep-alive') || __fwd_equal(ptr,size,'proxy-connection')
103
+ || __fwd_equal(ptr,size,'transfer-encoding') || __fwd_equal(ptr,size,'te') || __fwd_equal(ptr,size,'trailer')
104
+ || __fwd_equal(ptr,size,'upgrade') || __fwd_equal(ptr,size,'content-length') || __fwd_equal(ptr,size,'host')
105
+ || __fwd_equal(ptr,size,'proxy-authenticate') || __fwd_equal(ptr,size,'proxy-authorization');
106
+ }
107
+ // Decimal parsing stops at cap+1: huge declared sizes cannot overflow or wrap.
108
+ function __fwd_length(ptr: usize, size: i32, cap: i32): i32 {
109
+ if (size == 0) return -2;
110
+ let value = 0;
111
+ for (let i = 0; i < size; i++) {
112
+ const byte = load<u8>(ptr + i); if (byte < 48 || byte > 57) return -2;
113
+ value = min(cap + 1, value * 10 + byte - 48);
114
+ }
115
+ return value;
116
+ }
117
+ function __fwd_declared_request(): bool {
118
+ const name = memory.data<u8>([99,111,110,116,101,110,116,45,108,101,110,103,116,104]);
119
+ store<i64>(__fwd_io + 40, -1); store<i32>(__fwd_io + 48, 0);
120
+ const status = __pulse_request_header_values(__pulse_fastly_request_handle, name, 14, __fwd_headers, 16384, 0, __fwd_io + 40, __fwd_io + 48);
121
+ const count = load<i32>(__fwd_io + 48);
122
+ if (status != 0 || count < 0 || count > 16384 || (count > 0 && load<i64>(__fwd_io + 40) != -1)) { __fwd_fail(400); return false; }
123
+ if (count == 0) return true;
124
+ if (load<u8>(__fwd_headers + count - 1) != 0) { __fwd_fail(400); return false; }
125
+ __fwd_request_length = __fwd_length(__fwd_headers, count - 1, __FWD_REQUEST_MAX);
126
+ if (__fwd_request_length < 0) { __fwd_fail(400); return false; }
127
+ if (__fwd_request_length > __FWD_REQUEST_MAX) { __fwd_fail(413); return false; }
128
+ return true;
129
+ }
130
+ function __fwd_begin(index: i32, payload: __PulseFastlyValue): void {
131
+ __fwd_index = index;
132
+ const init = __pulse_fastly_value(__pulse_fastly_payload_field(payload, 'init'));
133
+ if (__fwd_reserved || __fwd_source < 0 || __pulse_fastly_payload_field(init, 'body') != __fwd_marker || __fwd_marker == 0) { __fwd_fail(400); return; }
134
+ __fwd_reserved = true;
135
+ __pulse_fetch_begin_deadline(index, init);
136
+ if (__pulse_fastly_last_error != 0 || !__fwd_remaining() || !__fwd_declared_request()) return;
137
+ const url = __pulse_fastly_utf8(__pulse_fastly_string(__pulse_fastly_payload_field(payload, 'url')));
138
+ const backend = __pulse_fastly_utf8(__pulse_fastly_backend(index));
139
+ if (fastly_http_req_new(__fwd_io + 52) != 0) { __fwd_fail(502); return; }
140
+ __fwd_request = load<i32>(__fwd_io + 52);
141
+ if (fastly_http_body_new(__fwd_io + 52) != 0) { __fwd_fail(502); return; }
142
+ __fwd_upload = load<i32>(__fwd_io + 52);
143
+ const method = memory.data<u8>([80,79,83,84]);
144
+ if (fastly_http_req_method_set(__fwd_request, method, 4) != 0 || fastly_http_req_uri_set(__fwd_request, changetype<usize>(url), url.byteLength) != 0) { __fwd_fail(502); return; }
145
+ const headers = __pulse_fastly_value(__pulse_fastly_payload_field(init, 'headers'));
146
+ let bytes = 0;
147
+ if (headers.kind == PULSE_VALUE_OBJECT) for (let i = 0; i < headers.keys.length; i++) {
148
+ const name = __pulse_fastly_utf8(headers.keys[i]), value = __pulse_fastly_utf8(__pulse_fastly_string(headers.values[i]));
149
+ bytes += name.byteLength + value.byteLength + 4;
150
+ if (i >= 64 || bytes > 16384 || __fwd_hop(changetype<usize>(name), name.byteLength)) { __fwd_fail(400); return; }
151
+ if (fastly_http_req_header_insert(__fwd_request, changetype<usize>(name), name.byteLength, changetype<usize>(value), value.byteLength) != 0) { __fwd_fail(400); return; }
152
+ }
153
+ if (!__fwd_remaining()) return;
154
+ __pulse_transport_slots[index] = null;
155
+ const status = __fwd_dispatch(__fwd_request, __fwd_upload, changetype<usize>(backend), backend.byteLength, __fwd_io + 52);
156
+ // send may consume the request even on failure. Cleanup makes only a best-effort
157
+ // close on that error path before any handle allocation/reuse can occur.
158
+ if (status != 0) { __pulse_transport_capture(__fwd_index, status, 'send'); __fwd_fail(502); return; }
159
+ __fwd_request = -1; __fwd_pending = load<i32>(__fwd_io + 52);
160
+ __pulse_fastly_pending[index] = __fwd_pending; __pulse_fastly_pending_mode[index] = PULSE_FASTLY_PENDING_ASYNC;
161
+ __fwd_remaining();
162
+ }
163
+ // Adopt early headers before considering readiness of the source or writer.
164
+ function __fwd_poll(): bool {
165
+ if (__fwd_pending < 0 || !__fwd_remaining()) return __fwd_response >= 0;
166
+ __pulse_send_error_detail_reset(__fwd_detail);
167
+ store<i32>(__fwd_done, 0);
168
+ const status = __pulse_fetch_poll(__fwd_pending, __fwd_detail, __fwd_done, __fwd_response_out, __fwd_body_out);
169
+ const done = load<i32>(__fwd_done);
170
+ if (status != 0) { __pulse_transport_capture(__fwd_index, status, 'poll', __fwd_detail); __fwd_pending = -1; __fwd_fail(502); return false; }
171
+ if (done != 0 && done != 1) { __fwd_fail(502); return false; }
172
+ if (done == 1) {
173
+ __fwd_response = load<i32>(__fwd_response_out); __fwd_body = load<i32>(__fwd_body_out); __fwd_pending = -1;
174
+ }
175
+ if (!__fwd_remaining()) return false;
176
+ return done == 1;
177
+ }
178
+ function __fwd_wait_io(handle: i32, upload: bool): bool {
179
+ while (__fwd_remaining() > 0) {
180
+ if (upload && __fwd_poll()) return false;
181
+ if (__fwd_failure != 0) return false;
182
+ store<i32>(__fwd_io + 52, -1);
183
+ if (__fwd_ready(handle, __fwd_io + 52) != 0) { __fwd_fail(502); return false; }
184
+ const ready = load<i32>(__fwd_io + 52);
185
+ if (ready == 1) return __fwd_remaining() > 0;
186
+ if (ready != 0) { __fwd_fail(502); return false; }
187
+ let count = 0;
188
+ if (upload && __fwd_pending >= 0) { store<i32>(__fwd_io + 56, __fwd_pending); count++; }
189
+ store<i32>(__fwd_io + 56 + count * 4, handle); count++;
190
+ const remaining = __fwd_remaining(); if (remaining == 0) return false;
191
+ const status = __pulse_fetch_select(__fwd_io + 56, count, remaining, __fwd_io + 64);
192
+ if (status != 0) { __fwd_fail(502); return false; }
193
+ const selected = load<i32>(__fwd_io + 64);
194
+ if (selected == -1) { __fwd_fail(504); return false; }
195
+ if (selected < 0 || selected >= count) { __fwd_fail(502); return false; }
196
+ }
197
+ return false;
198
+ }
199
+ function __fwd_copy(source: i32, sink: i32, cap: i32, declared: i32, upload: bool): bool {
200
+ let total = 0;
201
+ while (true) {
202
+ // Demand first; at most one raw chunk can be read ahead of the writer.
203
+ if (!__fwd_wait_io(sink, upload) || !__fwd_wait_io(source, upload)) return false;
204
+ const size = min(16384, cap - total + 1);
205
+ store<i32>(__fwd_io + 68, -1);
206
+ if (fastly_http_body_read(source, __fwd_buffer, size, __fwd_io + 68) != 0) { __fwd_fail(upload ? 400 : 502); return false; }
207
+ const read = load<i32>(__fwd_io + 68);
208
+ if (!__fwd_remaining()) return false;
209
+ if (read < 0 || read > size) { __fwd_fail(502); return false; }
210
+ if (read == 0) {
211
+ if (declared >= 0 && total != declared) { __fwd_fail(upload ? 400 : 502); return false; }
212
+ return true;
213
+ }
214
+ total += read;
215
+ if (total > cap) { __fwd_fail(upload ? 413 : 502); return false; }
216
+ if (declared >= 0 && total > declared) { __fwd_fail(upload ? 400 : 502); return false; }
217
+ let offset = 0;
218
+ while (offset < read) {
219
+ if (!__fwd_wait_io(sink, upload)) return false;
220
+ store<i32>(__fwd_io + 72, -1);
221
+ if (fastly_http_body_write(sink, __fwd_buffer + offset, read - offset, 0, __fwd_io + 72) != 0) { __fwd_fail(502); return false; }
222
+ const written = load<i32>(__fwd_io + 72);
223
+ if (!__fwd_remaining()) return false;
224
+ if (written <= 0 || written > read - offset) { __fwd_fail(502); return false; }
225
+ offset += written;
226
+ }
227
+ }
228
+ }
229
+ function __fwd_wait(): i32 {
230
+ if (__fwd_failure != 0 || __fwd_pending < 0) return 0;
231
+ const eof = __fwd_copy(__fwd_source, __fwd_upload, __FWD_REQUEST_MAX, __fwd_request_length, true);
232
+ __pulse_fetch_close_body(__fwd_source); __fwd_source = -1;
233
+ if (eof && __fwd_remaining()) {
234
+ const upload = __fwd_upload; __fwd_upload = -1;
235
+ if (__pulse_fetch_close_body(upload) != 0) __fwd_fail(502);
236
+ } else if (__fwd_upload >= 0) { __fwd_abandon(__fwd_upload); __fwd_upload = -1; }
237
+ while (__fwd_failure == 0 && __fwd_response < 0) {
238
+ if (__fwd_poll()) break;
239
+ if (__fwd_failure != 0 || !__fwd_wait_io(__fwd_pending, false)) break;
240
+ }
241
+ __pulse_fastly_pending_mode[__fwd_index] = PULSE_FASTLY_PENDING_NONE; __pulse_fastly_pending[__fwd_index] = 0;
242
+ if (__fwd_failure != 0 || !__fwd_remaining()) return 0;
243
+ const value = new __PulseFastlyValue(); value.kind = PULSE_VALUE_FETCH;
244
+ value.responseHandle = __fwd_response; value.bodyHandle = __fwd_body;
245
+ __fwd_result = __pulse_fastly_put(value); return __fwd_result;
246
+ }
247
+ function __fwd_response_headers(): bool {
248
+ store<i32>(__fwd_io + 52, 0);
249
+ if (fastly_http_resp_status_get(__fwd_response, __fwd_io + 52) != 0) { __fwd_fail(502); return false; }
250
+ __fwd_status = load<u16>(__fwd_io + 52);
251
+ if (__fwd_status < 200 || __fwd_status > 599) { __fwd_fail(502); return false; }
252
+ store<i64>(__fwd_io + 40, -1); store<i32>(__fwd_io + 48, -1);
253
+ if (__fwd_names(__fwd_response, __fwd_headers, 16384, 0, __fwd_io + 40, __fwd_io + 48) != 0) { __fwd_fail(502); return false; }
254
+ const names = load<i32>(__fwd_io + 48);
255
+ if (names < 0 || names > 16384 || (names > 0 && load<i64>(__fwd_io + 40) != -1)) { __fwd_fail(502); return false; }
256
+ let used = names, start = 0, total = 0, nameCount = 0;
257
+ for (let i = 0; i < names; i++) {
258
+ const byte = load<u8>(__fwd_headers + i);
259
+ if (byte != 0) { if (!__fwd_token(byte)) { __fwd_fail(502); return false; } continue; }
260
+ const name = __fwd_headers + start, length = i - start; start = i + 1;
261
+ if (length == 0 || ++nameCount > 64 || used >= 16384) { __fwd_fail(502); return false; }
262
+ store<i64>(__fwd_io + 40, -1); store<i32>(__fwd_io + 48, -1);
263
+ if (__fwd_values(__fwd_response, name, length, __fwd_headers + used, 16384 - used, 0, __fwd_io + 40, __fwd_io + 48) != 0) { __fwd_fail(502); return false; }
264
+ const size = load<i32>(__fwd_io + 48);
265
+ if (size <= 0 || size > 16384 - used || load<i64>(__fwd_io + 40) != -1) { __fwd_fail(502); return false; }
266
+ let valueStart = 0;
267
+ for (let j = 0; j < size; j++) {
268
+ const item = load<u8>(__fwd_headers + used + j);
269
+ if (item != 0) { if ((item < 32 && item != 9) || item == 127) { __fwd_fail(502); return false; } continue; }
270
+ const value = __fwd_headers + used + valueStart, valueSize = j - valueStart; valueStart = j + 1;
271
+ total += length + valueSize + 4;
272
+ if (__fwd_header_count >= 64 || total > 16384) { __fwd_fail(502); return false; }
273
+ const pair = __fwd_pairs + __fwd_header_count * 16; __fwd_header_count++;
274
+ store<usize>(pair, name); store<i32>(pair + 4, length); store<usize>(pair + 8, value); store<i32>(pair + 12, valueSize);
275
+ if (__fwd_equal(name, length, 'content-length')) {
276
+ if (__fwd_response_length != -1) { __fwd_fail(502); return false; }
277
+ __fwd_response_length = __fwd_length(value, valueSize, __FWD_RESPONSE_MAX);
278
+ if (__fwd_response_length < 0 || (__fwd_status != 304 && __fwd_response_length > __FWD_RESPONSE_MAX)) { __fwd_fail(502); return false; }
279
+ }
280
+ }
281
+ if (valueStart != size) { __fwd_fail(502); return false; }
282
+ used += size;
283
+ }
284
+ if (start != names || ((__fwd_status == 204 || __fwd_status == 205) && __fwd_response_length > 0)) { __fwd_fail(502); return false; }
285
+ return __fwd_remaining() > 0;
286
+ }
287
+ function __fwd_nominated(name: usize, length: i32): bool {
288
+ let nominated = false;
289
+ for (let i = 0; i < __fwd_header_count; i++) {
290
+ const pair = __fwd_pairs + i * 16;
291
+ if (!__fwd_equal(load<usize>(pair), load<i32>(pair + 4), 'connection')) continue;
292
+ const value = load<usize>(pair + 8), size = load<i32>(pair + 12);
293
+ let offset = 0;
294
+ while (offset < size) {
295
+ while (offset < size && (load<u8>(value + offset) == 32 || load<u8>(value + offset) == 9)) offset++;
296
+ const start = offset;
297
+ while (offset < size && __fwd_token(load<u8>(value + offset))) offset++;
298
+ const count = offset - start;
299
+ if (count == 0) { __fwd_fail(502); return false; }
300
+ if (count == length) {
301
+ let same = true;
302
+ for (let c = 0; c < count; c++) if (__fwd_lower(load<u8>(value + start + c)) != __fwd_lower(load<u8>(name + c))) same = false;
303
+ if (same) nominated = true;
304
+ }
305
+ while (offset < size && (load<u8>(value + offset) == 32 || load<u8>(value + offset) == 9)) offset++;
306
+ if (offset < size && (load<u8>(value + offset++) != 44 || offset == size)) { __fwd_fail(502); return false; }
307
+ }
308
+ }
309
+ return nominated;
310
+ }
311
+ function __fwd_send(): i32 {
312
+ if (!__fwd_response_headers()) { __fwd_error_response(); return 0; }
313
+ if (fastly_http_resp_new(__fwd_io + 52) != 0) { __fwd_fail(502); __fwd_error_response(); return 0; }
314
+ __fwd_output = load<i32>(__fwd_io + 52);
315
+ if (fastly_http_resp_status_set(__fwd_output, __fwd_status) != 0 || fastly_http_body_new(__fwd_io + 52) != 0) { __fwd_fail(502); __fwd_error_response(); return 0; }
316
+ __fwd_downstream = load<i32>(__fwd_io + 52);
317
+ for (let i = 0; i < __fwd_header_count; i++) {
318
+ const pair = __fwd_pairs + i * 16, name = load<usize>(pair), length = load<i32>(pair + 4);
319
+ const nominated = __fwd_nominated(name, length);
320
+ if (__fwd_failure != 0) break;
321
+ if (__fwd_hop(name, length) || nominated) continue;
322
+ if (fastly_http_resp_header_append(__fwd_output, name, length, load<usize>(pair + 8), load<i32>(pair + 12)) != 0) { __fwd_fail(502); break; }
323
+ }
324
+ __pulse_fetch_close_response(__fwd_response); __fwd_response = -1;
325
+ if (!__fwd_remaining()) { __fwd_error_response(); return 0; }
326
+ // Treat even an ambiguous send failure as committed: never emit a second
327
+ // response. The writable body remains ours until explicit EOF or abandon.
328
+ __fwd_committed = true;
329
+ const output = __fwd_output; __fwd_output = -1;
330
+ if (fastly_http_resp_send_downstream(output, __fwd_downstream, 1) != 0) { __pulse_fetch_close_response(output); __fwd_fail(502); __fwd_cleanup(); return 0; }
331
+ const bodyless = __fwd_status == 204 || __fwd_status == 205 || __fwd_status == 304;
332
+ const eof = __fwd_copy(__fwd_body, __fwd_downstream, bodyless ? 0 : __FWD_RESPONSE_MAX, bodyless ? 0 : __fwd_response_length, false);
333
+ __pulse_fetch_close_body(__fwd_body); __fwd_body = -1;
334
+ if (eof && __fwd_remaining()) {
335
+ const downstream = __fwd_downstream; __fwd_downstream = -1;
336
+ if (__pulse_fetch_close_body(downstream) != 0) __fwd_fail(502);
337
+ // Success is the host-handoff boundary. The handle is gone; there is no
338
+ // final-writer wait, delivery receipt, or post-handoff timeout guarantee.
339
+ }
340
+ __fwd_cleanup(); return 0;
341
+ }
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const {normalizeBodyForwarding, forwardingError} = require('../toolchain/body-forwarding.js');
5
+ const IMPORTS = ['fastly_http_req:send_async_streaming', 'fastly_http_body:abandon',
6
+ 'fastly_async_io:is_ready', 'fastly_http_resp:header_names_get'];
7
+ const enabled = plan => (plan?.capabilities || []).includes('request.body.forward');
8
+ function field(value, name) { return value?.entries?.find(entry => entry.key?.value === name)?.value; }
9
+ function validate(plan, options) {
10
+ const config = normalizeBodyForwarding(options.bodyForwarding, options.maxDurationMs);
11
+ if (!enabled(plan)) return;
12
+ if (!config) throw forwardingError('Fastly Native incoming forwarding requires fastly.bodyForwarding limits and maxDurationMs.');
13
+ const effects = plan.effects || [], effect = effects[0];
14
+ const init = effect?.inputs?.find(input => input.name === 'init')?.value;
15
+ const body = field(init, 'body'), method = field(init, 'method'), headers = field(init, 'headers');
16
+ if (effects.length !== 1 || effect.kind !== 'fetch' || effect.grouped
17
+ || effect.result?.mode !== 'return' || effect.result?.valueKind !== 'opaque-response'
18
+ || effect.resource?.kind !== 'literal' || options.bindings?.dynamicBackends
19
+ || body?.name !== 'request.body.forward-marker' || method?.kind !== 'literal' || method.value !== 'POST'
20
+ || init.entries.some(entry => !['method', 'body', 'headers', 'timeoutMs'].includes(entry.key?.value))
21
+ || (headers && (headers.kind !== 'object' || headers.entries.some(entry => entry.key?.kind !== 'literal' || entry.value?.kind !== 'literal' || typeof entry.value.value !== 'string')))) {
22
+ throw forwardingError('Fastly Native forwarding admits one terminal opaque POST fetch with inline req.body(), a static backend, and optional literal headers/timeoutMs; groups, decoding, reuse, and dynamic backends are unsupported.');
23
+ }
24
+ const entries = headers?.entries || [];
25
+ const hop = /^(connection|keep-alive|proxy-connection|transfer-encoding|te|trailer|upgrade|content-length|host|proxy-authenticate|proxy-authorization)$/i;
26
+ if (entries.length > 64 || entries.reduce((sum, entry) => sum + Buffer.byteLength(entry.key.value) + Buffer.byteLength(entry.value.value) + 4, 0) > 16384
27
+ || entries.some(entry => hop.test(entry.key.value) || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(entry.key.value) || /[\x00-\x08\x0a-\x1f\x7f]/.test(entry.value.value))) {
28
+ throw forwardingError('Forwarding request headers must fit 64 pairs/16 KiB and exclude hop-by-hop, framing and Host fields.');
29
+ }
30
+ // One marker evaluation owns the incoming body. Reject unused/duplicate markers
31
+ // too: they must not be dispatched later through another continuation.
32
+ let markers = 0;
33
+ function walk(value) { if (!value || typeof value !== 'object') return; if (value.name === 'request.body.forward-marker') markers++; for (const item of Object.values(value)) walk(item); }
34
+ walk(plan);
35
+ if (markers !== 1) throw forwardingError('Fastly Native forwarding requires exactly one incoming body consumer.');
36
+ }
37
+ function instrument(input, plan, bindings) {
38
+ if (!enabled(plan)) return input;
39
+ let source = input;
40
+ const replace = (before, after) => {
41
+ if (!source.includes(before)) throw new Error('Fastly body-forwarding boundary drift: ' + before.slice(0, 100));
42
+ source = source.replace(before, after);
43
+ };
44
+ for (const [name, args, result, body] of [
45
+ ['__pulse_fastly_fetch_begin', 'effectIndex: i32, payload: __PulseFastlyValue', 'void', '__fwd_begin(effectIndex, payload);'],
46
+ ['__pulse_fastly_wait_fetch', 'effectIndex: i32', 'i32', 'return __fwd_wait();']
47
+ ]) {
48
+ const line = source.split('\n').find(line => line.startsWith(`function ${name}(`));
49
+ if (!line || !line.endsWith('}')) throw new Error('Fastly forwarding function boundary drift: ' + name);
50
+ replace(line, `function ${name}(${args}): ${result} { ${body} }`);
51
+ }
52
+ replace('function __pulse_fastly_send_result(handle: i32): i32 {',
53
+ 'function __pulse_fastly_send_result(handle: i32): i32 { if (handle == __fwd_result && handle != 0) return __fwd_send();');
54
+ replace('function __pulse_fastly_jwt_send_error(): void {',
55
+ 'function __pulse_fastly_jwt_send_error(): void { if (__fwd_error_response()) return;');
56
+ replace('function __request_send_timeout(): void {',
57
+ 'function __request_send_timeout(): void { if (__fwd_committed) { __fwd_cleanup(); return; }');
58
+ replace(' __pulse_fastly_run_invocation()\n', ' __pulse_fastly_run_invocation()\n __fwd_cleanup()\n');
59
+ replace(' __pulse_fastly_request_body_handle = load<i32>(changetype<usize>(handles) + 4)',
60
+ ' __pulse_fastly_request_body_handle = load<i32>(changetype<usize>(handles) + 4)\n __fwd_source = __pulse_fastly_request_body_handle');
61
+ // Generic request-budget code must not wait for headers before driving upload.
62
+ const begin = source.indexOf('function __pulse_fastly_resolve_effect(');
63
+ const end = source.indexOf('\n}', begin);
64
+ if (begin < 0 || end < 0) throw new Error('Fastly forwarding effect boundary drift');
65
+ source = source.slice(0, begin) + 'function __pulse_fastly_resolve_effect(effectIndex: i32): i32 { return __fwd_wait(); }' + source.slice(end + 2);
66
+ return source + '\n' + `const __FWD_REQUEST_MAX: i32 = ${bindings.bodyForwarding.requestMaxBytes}\nconst __FWD_RESPONSE_MAX: i32 = ${bindings.bodyForwarding.responseMaxBytes}\n`
67
+ + fs.readFileSync(path.join(__dirname, 'native-body-forwarding.as.ts'), 'utf8');
68
+ }
69
+ module.exports = {IMPORTS, enabled, validate, instrument};