@astrojs/cloudflare 7.5.2 → 7.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/util.js CHANGED
@@ -1,18 +1,13 @@
1
- const isNode = typeof process === "object" && Object.prototype.toString.call(process) === "[object process]";
2
- function getProcessEnvProxy() {
3
- return new Proxy(
4
- {},
5
- {
6
- get: (target, prop) => {
7
- console.warn(
8
- // NOTE: \0 prevents Vite replacement
9
- `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization as the Cloudflare platform only provides the environment variables per request. Please move the environment variable access inside a function that's only called after a request has been received.`
10
- );
11
- }
12
- }
13
- );
1
+ export const isNode = typeof process === 'object' && Object.prototype.toString.call(process) === '[object process]';
2
+ export function getProcessEnvProxy() {
3
+ return new Proxy({}, {
4
+ get: (target, prop) => {
5
+ console.warn(
6
+ // NOTE: \0 prevents Vite replacement
7
+ `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization ` +
8
+ `as the Cloudflare platform only provides the environment variables per request. ` +
9
+ `Please move the environment variable access inside a function ` +
10
+ `that's only called after a request has been received.`);
11
+ },
12
+ });
14
13
  }
15
- export {
16
- getProcessEnvProxy,
17
- isNode
18
- };
@@ -1,15 +1,23 @@
1
- function deduplicatePatterns(patterns) {
2
- const openPatterns = [];
3
- return [...new Set(patterns)].sort((a, b) => a.length - b.length).filter((pattern) => {
4
- if (openPatterns.some((p) => p.test(pattern))) {
5
- return false;
6
- }
7
- if (pattern.endsWith("*")) {
8
- openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, ".*")}`));
9
- }
10
- return true;
11
- });
1
+ /**
2
+ * Remove duplicates and redundant patterns from an `include` or `exclude` list.
3
+ * Otherwise Cloudflare will throw an error on deployment. Plus, it saves more entries.
4
+ * E.g. `['/foo/*', '/foo/*', '/foo/bar'] => ['/foo/*']`
5
+ * @param patterns a list of `include` or `exclude` patterns
6
+ * @returns a deduplicated list of patterns
7
+ */
8
+ export function deduplicatePatterns(patterns) {
9
+ const openPatterns = [];
10
+ // A value in the set may only occur once; it is unique in the set's collection.
11
+ // ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
12
+ return [...new Set(patterns)]
13
+ .sort((a, b) => a.length - b.length)
14
+ .filter((pattern) => {
15
+ if (openPatterns.some((p) => p.test(pattern))) {
16
+ return false;
17
+ }
18
+ if (pattern.endsWith('*')) {
19
+ openPatterns.push(new RegExp(`^${pattern.replace(/(\*\/)*\*$/g, '.*')}`));
20
+ }
21
+ return true;
22
+ });
12
23
  }
13
- export {
14
- deduplicatePatterns
15
- };
@@ -1,68 +1,67 @@
1
- async function getCFObject(runtimeMode) {
2
- const CF_ENDPOINT = "https://workers.cloudflare.com/cf.json";
3
- const CF_FALLBACK = {
4
- asOrganization: "",
5
- asn: 395747,
6
- colo: "DFW",
7
- city: "Austin",
8
- region: "Texas",
9
- regionCode: "TX",
10
- metroCode: "635",
11
- postalCode: "78701",
12
- country: "US",
13
- continent: "NA",
14
- timezone: "America/Chicago",
15
- latitude: "30.27130",
16
- longitude: "-97.74260",
17
- clientTcpRtt: 0,
18
- httpProtocol: "HTTP/1.1",
19
- requestPriority: "weight=192;exclusive=0",
20
- tlsCipher: "AEAD-AES128-GCM-SHA256",
21
- tlsVersion: "TLSv1.3",
22
- tlsClientAuth: {
23
- certPresented: "0",
24
- certVerified: "NONE",
25
- certRevoked: "0",
26
- certIssuerDN: "",
27
- certSubjectDN: "",
28
- certIssuerDNRFC2253: "",
29
- certSubjectDNRFC2253: "",
30
- certIssuerDNLegacy: "",
31
- certSubjectDNLegacy: "",
32
- certSerial: "",
33
- certIssuerSerial: "",
34
- certSKI: "",
35
- certIssuerSKI: "",
36
- certFingerprintSHA1: "",
37
- certFingerprintSHA256: "",
38
- certNotBefore: "",
39
- certNotAfter: ""
40
- },
41
- edgeRequestKeepAliveStatus: 0,
42
- hostMetadata: void 0,
43
- clientTrustScore: 99,
44
- botManagement: {
45
- corporateProxy: false,
46
- verifiedBot: false,
47
- ja3Hash: "25b4882c2bcb50cd6b469ff28c596742",
48
- staticResource: false,
49
- detectionIds: [],
50
- score: 99
1
+ export async function getCFObject(runtimeMode) {
2
+ const CF_ENDPOINT = 'https://workers.cloudflare.com/cf.json';
3
+ const CF_FALLBACK = {
4
+ asOrganization: '',
5
+ asn: 395747,
6
+ colo: 'DFW',
7
+ city: 'Austin',
8
+ region: 'Texas',
9
+ regionCode: 'TX',
10
+ metroCode: '635',
11
+ postalCode: '78701',
12
+ country: 'US',
13
+ continent: 'NA',
14
+ timezone: 'America/Chicago',
15
+ latitude: '30.27130',
16
+ longitude: '-97.74260',
17
+ clientTcpRtt: 0,
18
+ httpProtocol: 'HTTP/1.1',
19
+ requestPriority: 'weight=192;exclusive=0',
20
+ tlsCipher: 'AEAD-AES128-GCM-SHA256',
21
+ tlsVersion: 'TLSv1.3',
22
+ tlsClientAuth: {
23
+ certPresented: '0',
24
+ certVerified: 'NONE',
25
+ certRevoked: '0',
26
+ certIssuerDN: '',
27
+ certSubjectDN: '',
28
+ certIssuerDNRFC2253: '',
29
+ certSubjectDNRFC2253: '',
30
+ certIssuerDNLegacy: '',
31
+ certSubjectDNLegacy: '',
32
+ certSerial: '',
33
+ certIssuerSerial: '',
34
+ certSKI: '',
35
+ certIssuerSKI: '',
36
+ certFingerprintSHA1: '',
37
+ certFingerprintSHA256: '',
38
+ certNotBefore: '',
39
+ certNotAfter: '',
40
+ },
41
+ edgeRequestKeepAliveStatus: 0,
42
+ hostMetadata: undefined,
43
+ clientTrustScore: 99,
44
+ botManagement: {
45
+ corporateProxy: false,
46
+ verifiedBot: false,
47
+ ja3Hash: '25b4882c2bcb50cd6b469ff28c596742',
48
+ staticResource: false,
49
+ detectionIds: [],
50
+ score: 99,
51
+ },
52
+ };
53
+ if (runtimeMode === 'local') {
54
+ return CF_FALLBACK;
51
55
  }
52
- };
53
- if (runtimeMode === "local") {
54
- return CF_FALLBACK;
55
- } else if (runtimeMode === "remote") {
56
- try {
57
- const res = await fetch(CF_ENDPOINT);
58
- const cfText = await res.text();
59
- const storedCf = JSON.parse(cfText);
60
- return storedCf;
61
- } catch (e) {
62
- return CF_FALLBACK;
56
+ else if (runtimeMode === 'remote') {
57
+ try {
58
+ const res = await fetch(CF_ENDPOINT);
59
+ const cfText = await res.text();
60
+ const storedCf = JSON.parse(cfText);
61
+ return storedCf;
62
+ }
63
+ catch (e) {
64
+ return CF_FALLBACK;
65
+ }
63
66
  }
64
- }
65
67
  }
66
- export {
67
- getCFObject
68
- };
@@ -1,144 +1,149 @@
1
- import TOML from "@iarna/toml";
2
- import dotenv from "dotenv";
3
- import { findUpSync } from "find-up";
4
- import * as fs from "node:fs";
5
- import { dirname, resolve } from "node:path";
1
+ /**
2
+ * This file is a derivative work of wrangler by Cloudflare
3
+ * An upstream request for exposing this API was made here:
4
+ * https://github.com/cloudflare/workers-sdk/issues/3897
5
+ *
6
+ * Until further notice, we will be using this file as a workaround
7
+ * TODO: Tackle this file, once their is an decision on the upstream request
8
+ */
9
+ import TOML from '@iarna/toml';
10
+ import dotenv from 'dotenv';
11
+ import { findUpSync } from 'find-up';
12
+ import * as fs from 'node:fs';
13
+ import { dirname, resolve } from 'node:path';
6
14
  let _wrangler;
7
15
  function findWranglerToml(referencePath = process.cwd(), preferJson = false) {
8
- if (preferJson) {
9
- return findUpSync(`wrangler.json`, { cwd: referencePath }) ?? findUpSync(`wrangler.toml`, { cwd: referencePath });
10
- }
11
- return findUpSync(`wrangler.toml`, { cwd: referencePath });
16
+ if (preferJson) {
17
+ return (findUpSync(`wrangler.json`, { cwd: referencePath }) ??
18
+ findUpSync(`wrangler.toml`, { cwd: referencePath }));
19
+ }
20
+ return findUpSync(`wrangler.toml`, { cwd: referencePath });
12
21
  }
13
22
  class ParseError extends Error {
14
- text;
15
- notes;
16
- location;
17
- kind;
18
- constructor({ text, notes, location, kind }) {
19
- super(text);
20
- this.name = this.constructor.name;
21
- this.text = text;
22
- this.notes = notes ?? [];
23
- this.location = location;
24
- this.kind = kind ?? "error";
25
- }
23
+ text;
24
+ notes;
25
+ location;
26
+ kind;
27
+ constructor({ text, notes, location, kind }) {
28
+ super(text);
29
+ this.name = this.constructor.name;
30
+ this.text = text;
31
+ this.notes = notes ?? [];
32
+ this.location = location;
33
+ this.kind = kind ?? 'error';
34
+ }
26
35
  }
27
- const TOML_ERROR_NAME = "TomlError";
28
- const TOML_ERROR_SUFFIX = " at row ";
36
+ const TOML_ERROR_NAME = 'TomlError';
37
+ const TOML_ERROR_SUFFIX = ' at row ';
29
38
  function parseTOML(input, file) {
30
- try {
31
- const normalizedInput = input.replace(/\r\n/g, "\n");
32
- return TOML.parse(normalizedInput);
33
- } catch (err) {
34
- const { name, message, line, col } = err;
35
- if (name !== TOML_ERROR_NAME) {
36
- throw err;
39
+ try {
40
+ // Normalize CRLF to LF to avoid hitting https://github.com/iarna/iarna-toml/issues/33.
41
+ const normalizedInput = input.replace(/\r\n/g, '\n');
42
+ return TOML.parse(normalizedInput);
43
+ }
44
+ catch (err) {
45
+ const { name, message, line, col } = err;
46
+ if (name !== TOML_ERROR_NAME) {
47
+ throw err;
48
+ }
49
+ const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
50
+ const lineText = input.split('\n')[line];
51
+ const location = {
52
+ lineText,
53
+ line: line + 1,
54
+ column: col - 1,
55
+ file,
56
+ fileText: input,
57
+ };
58
+ throw new ParseError({ text, location });
37
59
  }
38
- const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
39
- const lineText = input.split("\n")[line];
40
- const location = {
41
- lineText,
42
- line: line + 1,
43
- column: col - 1,
44
- file,
45
- fileText: input
46
- };
47
- throw new ParseError({ text, location });
48
- }
49
60
  }
50
61
  function tryLoadDotEnv(path) {
51
- try {
52
- const parsed = dotenv.parse(fs.readFileSync(path));
53
- return { path, parsed };
54
- } catch (e) {
55
- }
62
+ try {
63
+ const parsed = dotenv.parse(fs.readFileSync(path));
64
+ return { path, parsed };
65
+ }
66
+ catch (e) {
67
+ // logger.debug(`Failed to load .env file "${path}":`, e);
68
+ }
56
69
  }
57
- function loadDotEnv(path) {
58
- return tryLoadDotEnv(path);
70
+ /**
71
+ * Loads a dotenv file from <path>, preferring to read <path>.<environment> if
72
+ * <environment> is defined and that file exists.
73
+ */
74
+ export function loadDotEnv(path) {
75
+ return tryLoadDotEnv(path);
59
76
  }
60
77
  function getVarsForDev(config, configPath) {
61
- const configDir = resolve(dirname(configPath ?? "."));
62
- const devVarsPath = resolve(configDir, ".dev.vars");
63
- const loaded = loadDotEnv(devVarsPath);
64
- if (loaded !== void 0) {
65
- return {
66
- ...config.vars,
67
- ...loaded.parsed
68
- };
69
- } else {
70
- return config.vars;
71
- }
78
+ const configDir = resolve(dirname(configPath ?? '.'));
79
+ const devVarsPath = resolve(configDir, '.dev.vars');
80
+ const loaded = loadDotEnv(devVarsPath);
81
+ if (loaded !== undefined) {
82
+ return {
83
+ ...config.vars,
84
+ ...loaded.parsed,
85
+ };
86
+ }
87
+ else {
88
+ return config.vars;
89
+ }
72
90
  }
73
91
  function parseConfig() {
74
- if (_wrangler)
75
- return _wrangler;
76
- let rawConfig;
77
- const configPath = findWranglerToml(process.cwd(), false);
78
- if (!configPath) {
79
- throw new Error("Could not find wrangler.toml");
80
- }
81
- if (configPath?.endsWith("toml")) {
82
- rawConfig = parseTOML(fs.readFileSync(configPath).toString(), configPath);
83
- }
84
- _wrangler = { rawConfig, configPath };
85
- return { rawConfig, configPath };
92
+ if (_wrangler)
93
+ return _wrangler;
94
+ let rawConfig;
95
+ const configPath = findWranglerToml(process.cwd(), false); // false = args.experimentalJsonConfig
96
+ if (!configPath) {
97
+ throw new Error('Could not find wrangler.toml');
98
+ }
99
+ // Load the configuration from disk if available
100
+ if (configPath?.endsWith('toml')) {
101
+ rawConfig = parseTOML(fs.readFileSync(configPath).toString(), configPath);
102
+ }
103
+ _wrangler = { rawConfig, configPath };
104
+ return { rawConfig, configPath };
86
105
  }
87
- async function getEnvVars() {
88
- const { rawConfig, configPath } = parseConfig();
89
- const vars = getVarsForDev(rawConfig, configPath);
90
- return vars;
106
+ export async function getEnvVars() {
107
+ const { rawConfig, configPath } = parseConfig();
108
+ const vars = getVarsForDev(rawConfig, configPath);
109
+ return vars;
91
110
  }
92
- async function getD1Bindings() {
93
- const { rawConfig } = parseConfig();
94
- if (!rawConfig)
95
- return [];
96
- if (!rawConfig?.d1_databases)
97
- return [];
98
- const bindings = (rawConfig?.d1_databases).map(
99
- (binding) => binding.binding
100
- );
101
- return bindings;
111
+ export async function getD1Bindings() {
112
+ const { rawConfig } = parseConfig();
113
+ if (!rawConfig)
114
+ return [];
115
+ if (!rawConfig?.d1_databases)
116
+ return [];
117
+ const bindings = (rawConfig?.d1_databases).map((binding) => binding.binding);
118
+ return bindings;
102
119
  }
103
- async function getR2Bindings() {
104
- const { rawConfig } = parseConfig();
105
- if (!rawConfig)
106
- return [];
107
- if (!rawConfig?.r2_buckets)
108
- return [];
109
- const bindings = (rawConfig?.r2_buckets).map(
110
- (binding) => binding.binding
111
- );
112
- return bindings;
120
+ export async function getR2Bindings() {
121
+ const { rawConfig } = parseConfig();
122
+ if (!rawConfig)
123
+ return [];
124
+ if (!rawConfig?.r2_buckets)
125
+ return [];
126
+ const bindings = (rawConfig?.r2_buckets).map((binding) => binding.binding);
127
+ return bindings;
113
128
  }
114
- async function getKVBindings() {
115
- const { rawConfig } = parseConfig();
116
- if (!rawConfig)
117
- return [];
118
- if (!rawConfig?.kv_namespaces)
119
- return [];
120
- const bindings = (rawConfig?.kv_namespaces).map(
121
- (binding) => binding.binding
122
- );
123
- return bindings;
129
+ export async function getKVBindings() {
130
+ const { rawConfig } = parseConfig();
131
+ if (!rawConfig)
132
+ return [];
133
+ if (!rawConfig?.kv_namespaces)
134
+ return [];
135
+ const bindings = (rawConfig?.kv_namespaces).map((binding) => binding.binding);
136
+ return bindings;
124
137
  }
125
- function getDOBindings() {
126
- const { rawConfig } = parseConfig();
127
- if (!rawConfig)
128
- return {};
129
- if (!rawConfig?.durable_objects)
130
- return {};
131
- const output = new Object({});
132
- for (const binding of rawConfig?.durable_objects.bindings) {
133
- Reflect.set(output, binding.name, { className: binding.class_name });
134
- }
135
- return output;
138
+ export function getDOBindings() {
139
+ const { rawConfig } = parseConfig();
140
+ if (!rawConfig)
141
+ return {};
142
+ if (!rawConfig?.durable_objects)
143
+ return {};
144
+ const output = new Object({});
145
+ for (const binding of rawConfig?.durable_objects.bindings) {
146
+ Reflect.set(output, binding.name, { className: binding.class_name });
147
+ }
148
+ return output;
136
149
  }
137
- export {
138
- getD1Bindings,
139
- getDOBindings,
140
- getEnvVars,
141
- getKVBindings,
142
- getR2Bindings,
143
- loadDotEnv
144
- };
@@ -1,6 +1,3 @@
1
- function prependForwardSlash(path) {
2
- return path[0] === "/" ? path : "/" + path;
1
+ export function prependForwardSlash(path) {
2
+ return path[0] === '/' ? path : '/' + path;
3
3
  }
4
- export {
5
- prependForwardSlash
6
- };
@@ -1,25 +1,23 @@
1
- import esbuild from "esbuild";
2
- import { basename } from "node:path";
3
- function rewriteWasmImportPath({
4
- relativePathToAssets
5
- }) {
6
- return {
7
- name: "wasm-loader",
8
- setup(build) {
9
- build.onResolve({ filter: /.*\.wasm.mjs$/ }, (args) => {
10
- const updatedPath = [
11
- relativePathToAssets.replaceAll("\\", "/"),
12
- basename(args.path).replace(/\.mjs$/, "")
13
- ].join("/");
14
- return {
15
- path: updatedPath,
16
- external: true
17
- // mark it as external in the bundle
18
- };
19
- });
20
- }
21
- };
1
+ import esbuild from 'esbuild';
2
+ import { basename } from 'node:path';
3
+ /**
4
+ *
5
+ * @param relativePathToAssets - relative path from the final location for the current esbuild output bundle, to the assets directory.
6
+ */
7
+ export function rewriteWasmImportPath({ relativePathToAssets, }) {
8
+ return {
9
+ name: 'wasm-loader',
10
+ setup(build) {
11
+ build.onResolve({ filter: /.*\.wasm.mjs$/ }, (args) => {
12
+ const updatedPath = [
13
+ relativePathToAssets.replaceAll('\\', '/'),
14
+ basename(args.path).replace(/\.mjs$/, ''),
15
+ ].join('/');
16
+ return {
17
+ path: updatedPath,
18
+ external: true, // mark it as external in the bundle
19
+ };
20
+ });
21
+ },
22
+ };
22
23
  }
23
- export {
24
- rewriteWasmImportPath
25
- };