Initial commit
This commit is contained in:
3
node_modules/astro/dist/actions/runtime/client.d.ts
generated
vendored
Normal file
3
node_modules/astro/dist/actions/runtime/client.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './shared.js';
|
||||
export declare function defineAction(): void;
|
||||
export declare function getActionContext(): void;
|
||||
11
node_modules/astro/dist/actions/runtime/client.js
generated
vendored
Normal file
11
node_modules/astro/dist/actions/runtime/client.js
generated
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
export * from "./shared.js";
|
||||
function defineAction() {
|
||||
throw new Error("[astro:action] `defineAction()` unexpectedly used on the client.");
|
||||
}
|
||||
function getActionContext() {
|
||||
throw new Error("[astro:action] `getActionContext()` unexpectedly used on the client.");
|
||||
}
|
||||
export {
|
||||
defineAction,
|
||||
getActionContext
|
||||
};
|
||||
2
node_modules/astro/dist/actions/runtime/route.d.ts
generated
vendored
Normal file
2
node_modules/astro/dist/actions/runtime/route.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import type { APIRoute } from '../../types/public/common.js';
|
||||
export declare const POST: APIRoute;
|
||||
23
node_modules/astro/dist/actions/runtime/route.js
generated
vendored
Normal file
23
node_modules/astro/dist/actions/runtime/route.js
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
import { getActionContext } from "./server.js";
|
||||
const POST = async (context) => {
|
||||
const { action, serializeActionResult } = getActionContext(context);
|
||||
if (action?.calledFrom !== "rpc") {
|
||||
return new Response("Not found", { status: 404 });
|
||||
}
|
||||
const result = await action.handler();
|
||||
const serialized = serializeActionResult(result);
|
||||
if (serialized.type === "empty") {
|
||||
return new Response(null, {
|
||||
status: serialized.status
|
||||
});
|
||||
}
|
||||
return new Response(serialized.body, {
|
||||
status: serialized.status,
|
||||
headers: {
|
||||
"Content-Type": serialized.contentType
|
||||
}
|
||||
});
|
||||
};
|
||||
export {
|
||||
POST
|
||||
};
|
||||
61
node_modules/astro/dist/actions/runtime/server.d.ts
generated
vendored
Normal file
61
node_modules/astro/dist/actions/runtime/server.d.ts
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
import { z } from 'zod';
|
||||
import type { APIContext } from '../../types/public/index.js';
|
||||
import { deserializeActionResult, type SafeResult, type SerializedActionResult, serializeActionResult } from './shared.js';
|
||||
import { type ActionAPIContext, type ErrorInferenceObject, type MaybePromise } from './utils.js';
|
||||
export * from './shared.js';
|
||||
export type ActionAccept = 'form' | 'json';
|
||||
export type ActionHandler<TInputSchema, TOutput> = TInputSchema extends z.ZodType ? (input: z.infer<TInputSchema>, context: ActionAPIContext) => MaybePromise<TOutput> : (input: any, context: ActionAPIContext) => MaybePromise<TOutput>;
|
||||
export type ActionReturnType<T extends ActionHandler<any, any>> = Awaited<ReturnType<T>>;
|
||||
export type InferKey = '__internalInfer';
|
||||
/**
|
||||
* Infers the type of an action's input based on its Zod schema
|
||||
*
|
||||
* @see https://docs.astro.build/en/reference/modules/astro-actions/#actioninputschema
|
||||
*/
|
||||
export type ActionInputSchema<T extends ActionClient<any, any, any>> = T extends {
|
||||
[key in InferKey]: any;
|
||||
} ? T[InferKey] : never;
|
||||
export type ActionClient<TOutput, TAccept extends ActionAccept | undefined, TInputSchema extends z.ZodType | undefined> = TInputSchema extends z.ZodType ? ((input: TAccept extends 'form' ? FormData : z.input<TInputSchema>) => Promise<SafeResult<z.input<TInputSchema> extends ErrorInferenceObject ? z.input<TInputSchema> : ErrorInferenceObject, Awaited<TOutput>>>) & {
|
||||
queryString: string;
|
||||
orThrow: (input: TAccept extends 'form' ? FormData : z.input<TInputSchema>) => Promise<Awaited<TOutput>>;
|
||||
} & {
|
||||
[key in InferKey]: TInputSchema;
|
||||
} : ((input?: any) => Promise<SafeResult<never, Awaited<TOutput>>>) & {
|
||||
orThrow: (input?: any) => Promise<Awaited<TOutput>>;
|
||||
};
|
||||
export declare function defineAction<TOutput, TAccept extends ActionAccept | undefined = undefined, TInputSchema extends z.ZodType | undefined = TAccept extends 'form' ? z.ZodType<FormData> : undefined>({ accept, input: inputSchema, handler, }: {
|
||||
input?: TInputSchema;
|
||||
accept?: TAccept;
|
||||
handler: ActionHandler<TInputSchema, TOutput>;
|
||||
}): ActionClient<TOutput, TAccept, TInputSchema> & string;
|
||||
/** Transform form data to an object based on a Zod schema. */
|
||||
export declare function formDataToObject<T extends z.AnyZodObject>(formData: FormData, schema: T): Record<string, unknown>;
|
||||
export type AstroActionContext = {
|
||||
/** Information about an incoming action request. */
|
||||
action?: {
|
||||
/** Whether an action was called using an RPC function or by using an HTML form action. */
|
||||
calledFrom: 'rpc' | 'form';
|
||||
/** The name of the action. Useful to track the source of an action result during a redirect. */
|
||||
name: string;
|
||||
/** Programmatically call the action to get the result. */
|
||||
handler: () => Promise<SafeResult<any, any>>;
|
||||
};
|
||||
/**
|
||||
* Manually set the action result accessed via `getActionResult()`.
|
||||
* Calling this function from middleware will disable Astro's own action result handling.
|
||||
*/
|
||||
setActionResult(actionName: string, actionResult: SerializedActionResult): void;
|
||||
/**
|
||||
* Serialize an action result to stored in a cookie or session.
|
||||
* Also used to pass a result to Astro templates via `setActionResult()`.
|
||||
*/
|
||||
serializeActionResult: typeof serializeActionResult;
|
||||
/**
|
||||
* Deserialize an action result to access data and error objects.
|
||||
*/
|
||||
deserializeActionResult: typeof deserializeActionResult;
|
||||
};
|
||||
/**
|
||||
* Access information about Action requests from middleware.
|
||||
*/
|
||||
export declare function getActionContext(context: APIContext): AstroActionContext;
|
||||
225
node_modules/astro/dist/actions/runtime/server.js
generated
vendored
Normal file
225
node_modules/astro/dist/actions/runtime/server.js
generated
vendored
Normal file
@@ -0,0 +1,225 @@
|
||||
import { z } from "zod";
|
||||
import { shouldAppendForwardSlash } from "../../core/build/util.js";
|
||||
import { AstroError } from "../../core/errors/errors.js";
|
||||
import { ActionCalledFromServerError, ActionNotFoundError } from "../../core/errors/errors-data.js";
|
||||
import { removeTrailingForwardSlash } from "../../core/path.js";
|
||||
import { apiContextRoutesSymbol } from "../../core/render-context.js";
|
||||
import { ACTION_RPC_ROUTE_PATTERN } from "../consts.js";
|
||||
import {
|
||||
ACTION_QUERY_PARAMS,
|
||||
ActionError,
|
||||
ActionInputError,
|
||||
callSafely,
|
||||
deserializeActionResult,
|
||||
serializeActionResult
|
||||
} from "./shared.js";
|
||||
import {
|
||||
ACTION_API_CONTEXT_SYMBOL,
|
||||
formContentTypes,
|
||||
hasContentType,
|
||||
isActionAPIContext
|
||||
} from "./utils.js";
|
||||
export * from "./shared.js";
|
||||
function defineAction({
|
||||
accept,
|
||||
input: inputSchema,
|
||||
handler
|
||||
}) {
|
||||
const serverHandler = accept === "form" ? getFormServerHandler(handler, inputSchema) : getJsonServerHandler(handler, inputSchema);
|
||||
async function safeServerHandler(unparsedInput) {
|
||||
if (typeof this === "function" || !isActionAPIContext(this)) {
|
||||
throw new AstroError(ActionCalledFromServerError);
|
||||
}
|
||||
return callSafely(() => serverHandler(unparsedInput, this));
|
||||
}
|
||||
Object.assign(safeServerHandler, {
|
||||
orThrow(unparsedInput) {
|
||||
if (typeof this === "function") {
|
||||
throw new AstroError(ActionCalledFromServerError);
|
||||
}
|
||||
return serverHandler(unparsedInput, this);
|
||||
}
|
||||
});
|
||||
return safeServerHandler;
|
||||
}
|
||||
function getFormServerHandler(handler, inputSchema) {
|
||||
return async (unparsedInput, context) => {
|
||||
if (!(unparsedInput instanceof FormData)) {
|
||||
throw new ActionError({
|
||||
code: "UNSUPPORTED_MEDIA_TYPE",
|
||||
message: "This action only accepts FormData."
|
||||
});
|
||||
}
|
||||
if (!inputSchema) return await handler(unparsedInput, context);
|
||||
const baseSchema = unwrapBaseObjectSchema(inputSchema, unparsedInput);
|
||||
const parsed = await inputSchema.safeParseAsync(
|
||||
baseSchema instanceof z.ZodObject ? formDataToObject(unparsedInput, baseSchema) : unparsedInput
|
||||
);
|
||||
if (!parsed.success) {
|
||||
throw new ActionInputError(parsed.error.issues);
|
||||
}
|
||||
return await handler(parsed.data, context);
|
||||
};
|
||||
}
|
||||
function getJsonServerHandler(handler, inputSchema) {
|
||||
return async (unparsedInput, context) => {
|
||||
if (unparsedInput instanceof FormData) {
|
||||
throw new ActionError({
|
||||
code: "UNSUPPORTED_MEDIA_TYPE",
|
||||
message: "This action only accepts JSON."
|
||||
});
|
||||
}
|
||||
if (!inputSchema) return await handler(unparsedInput, context);
|
||||
const parsed = await inputSchema.safeParseAsync(unparsedInput);
|
||||
if (!parsed.success) {
|
||||
throw new ActionInputError(parsed.error.issues);
|
||||
}
|
||||
return await handler(parsed.data, context);
|
||||
};
|
||||
}
|
||||
function formDataToObject(formData, schema) {
|
||||
const obj = schema._def.unknownKeys === "passthrough" ? Object.fromEntries(formData.entries()) : {};
|
||||
for (const [key, baseValidator] of Object.entries(schema.shape)) {
|
||||
let validator = baseValidator;
|
||||
while (validator instanceof z.ZodOptional || validator instanceof z.ZodNullable || validator instanceof z.ZodDefault) {
|
||||
if (validator instanceof z.ZodDefault && !formData.has(key)) {
|
||||
obj[key] = validator._def.defaultValue();
|
||||
}
|
||||
validator = validator._def.innerType;
|
||||
}
|
||||
if (!formData.has(key) && key in obj) {
|
||||
continue;
|
||||
} else if (validator instanceof z.ZodBoolean) {
|
||||
const val = formData.get(key);
|
||||
obj[key] = val === "true" ? true : val === "false" ? false : formData.has(key);
|
||||
} else if (validator instanceof z.ZodArray) {
|
||||
obj[key] = handleFormDataGetAll(key, formData, validator);
|
||||
} else {
|
||||
obj[key] = handleFormDataGet(key, formData, validator, baseValidator);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
function handleFormDataGetAll(key, formData, validator) {
|
||||
const entries = Array.from(formData.getAll(key));
|
||||
const elementValidator = validator._def.type;
|
||||
if (elementValidator instanceof z.ZodNumber) {
|
||||
return entries.map(Number);
|
||||
} else if (elementValidator instanceof z.ZodBoolean) {
|
||||
return entries.map(Boolean);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
function handleFormDataGet(key, formData, validator, baseValidator) {
|
||||
const value = formData.get(key);
|
||||
if (!value) {
|
||||
return baseValidator instanceof z.ZodOptional ? void 0 : null;
|
||||
}
|
||||
return validator instanceof z.ZodNumber ? Number(value) : value;
|
||||
}
|
||||
function unwrapBaseObjectSchema(schema, unparsedInput) {
|
||||
while (schema instanceof z.ZodEffects || schema instanceof z.ZodPipeline) {
|
||||
if (schema instanceof z.ZodEffects) {
|
||||
schema = schema._def.schema;
|
||||
}
|
||||
if (schema instanceof z.ZodPipeline) {
|
||||
schema = schema._def.in;
|
||||
}
|
||||
}
|
||||
if (schema instanceof z.ZodDiscriminatedUnion) {
|
||||
const typeKey = schema._def.discriminator;
|
||||
const typeValue = unparsedInput.get(typeKey);
|
||||
if (typeof typeValue !== "string") return schema;
|
||||
const objSchema = schema._def.optionsMap.get(typeValue);
|
||||
if (!objSchema) return schema;
|
||||
return objSchema;
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
function getActionContext(context) {
|
||||
const callerInfo = getCallerInfo(context);
|
||||
const actionResultAlreadySet = Boolean(context.locals._actionPayload);
|
||||
let action = void 0;
|
||||
if (callerInfo && context.request.method === "POST" && !actionResultAlreadySet) {
|
||||
action = {
|
||||
calledFrom: callerInfo.from,
|
||||
name: callerInfo.name,
|
||||
handler: async () => {
|
||||
const pipeline = Reflect.get(context, apiContextRoutesSymbol);
|
||||
const callerInfoName = shouldAppendForwardSlash(
|
||||
pipeline.manifest.trailingSlash,
|
||||
pipeline.manifest.buildFormat
|
||||
) ? removeTrailingForwardSlash(callerInfo.name) : callerInfo.name;
|
||||
let baseAction;
|
||||
try {
|
||||
baseAction = await pipeline.getAction(callerInfoName);
|
||||
} catch (error) {
|
||||
if (error instanceof Error && "name" in error && typeof error.name === "string" && error.name === ActionNotFoundError.name) {
|
||||
return { data: void 0, error: new ActionError({ code: "NOT_FOUND" }) };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
let input;
|
||||
try {
|
||||
input = await parseRequestBody(context.request);
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError) {
|
||||
return { data: void 0, error: new ActionError({ code: "UNSUPPORTED_MEDIA_TYPE" }) };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const omitKeys = ["props", "getActionResult", "callAction", "redirect"];
|
||||
const actionAPIContext = Object.create(
|
||||
Object.getPrototypeOf(context),
|
||||
Object.fromEntries(
|
||||
Object.entries(Object.getOwnPropertyDescriptors(context)).filter(
|
||||
([key]) => !omitKeys.includes(key)
|
||||
)
|
||||
)
|
||||
);
|
||||
Reflect.set(actionAPIContext, ACTION_API_CONTEXT_SYMBOL, true);
|
||||
const handler = baseAction.bind(actionAPIContext);
|
||||
return handler(input);
|
||||
}
|
||||
};
|
||||
}
|
||||
function setActionResult(actionName, actionResult) {
|
||||
context.locals._actionPayload = {
|
||||
actionResult,
|
||||
actionName
|
||||
};
|
||||
}
|
||||
return {
|
||||
action,
|
||||
setActionResult,
|
||||
serializeActionResult,
|
||||
deserializeActionResult
|
||||
};
|
||||
}
|
||||
function getCallerInfo(ctx) {
|
||||
if (ctx.routePattern === ACTION_RPC_ROUTE_PATTERN) {
|
||||
return { from: "rpc", name: ctx.url.pathname.replace(/^.*\/_actions\//, "") };
|
||||
}
|
||||
const queryParam = ctx.url.searchParams.get(ACTION_QUERY_PARAMS.actionName);
|
||||
if (queryParam) {
|
||||
return { from: "form", name: queryParam };
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
async function parseRequestBody(request) {
|
||||
const contentType = request.headers.get("content-type");
|
||||
const contentLength = request.headers.get("Content-Length");
|
||||
if (!contentType) return void 0;
|
||||
if (hasContentType(contentType, formContentTypes)) {
|
||||
return await request.clone().formData();
|
||||
}
|
||||
if (hasContentType(contentType, ["application/json"])) {
|
||||
return contentLength === "0" ? void 0 : await request.clone().json();
|
||||
}
|
||||
throw new TypeError("Unsupported content type");
|
||||
}
|
||||
export {
|
||||
defineAction,
|
||||
formDataToObject,
|
||||
getActionContext
|
||||
};
|
||||
60
node_modules/astro/dist/actions/runtime/shared.d.ts
generated
vendored
Normal file
60
node_modules/astro/dist/actions/runtime/shared.d.ts
generated
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
import type { z } from 'zod';
|
||||
import { AstroError } from '../../core/errors/errors.js';
|
||||
import { appendForwardSlash as _appendForwardSlash } from '../../core/path.js';
|
||||
import type { ActionAPIContext as _ActionAPIContext, ErrorInferenceObject, MaybePromise } from './utils.js';
|
||||
export type ActionAPIContext = _ActionAPIContext;
|
||||
export declare const ACTION_QUERY_PARAMS: {
|
||||
actionName: string;
|
||||
actionPayload: string;
|
||||
};
|
||||
export declare const appendForwardSlash: typeof _appendForwardSlash;
|
||||
export declare const ACTION_ERROR_CODES: readonly ["BAD_REQUEST", "UNAUTHORIZED", "PAYMENT_REQUIRED", "FORBIDDEN", "NOT_FOUND", "METHOD_NOT_ALLOWED", "NOT_ACCEPTABLE", "PROXY_AUTHENTICATION_REQUIRED", "REQUEST_TIMEOUT", "CONFLICT", "GONE", "LENGTH_REQUIRED", "PRECONDITION_FAILED", "CONTENT_TOO_LARGE", "URI_TOO_LONG", "UNSUPPORTED_MEDIA_TYPE", "RANGE_NOT_SATISFIABLE", "EXPECTATION_FAILED", "MISDIRECTED_REQUEST", "UNPROCESSABLE_CONTENT", "LOCKED", "FAILED_DEPENDENCY", "TOO_EARLY", "UPGRADE_REQUIRED", "PRECONDITION_REQUIRED", "TOO_MANY_REQUESTS", "REQUEST_HEADER_FIELDS_TOO_LARGE", "UNAVAILABLE_FOR_LEGAL_REASONS", "INTERNAL_SERVER_ERROR", "NOT_IMPLEMENTED", "BAD_GATEWAY", "SERVICE_UNAVAILABLE", "GATEWAY_TIMEOUT", "HTTP_VERSION_NOT_SUPPORTED", "VARIANT_ALSO_NEGOTIATES", "INSUFFICIENT_STORAGE", "LOOP_DETECTED", "NETWORK_AUTHENTICATION_REQUIRED"];
|
||||
export type ActionErrorCode = (typeof ACTION_ERROR_CODES)[number];
|
||||
export declare class ActionError<_T extends ErrorInferenceObject = ErrorInferenceObject> extends Error {
|
||||
type: string;
|
||||
code: ActionErrorCode;
|
||||
status: number;
|
||||
constructor(params: {
|
||||
message?: string;
|
||||
code: ActionErrorCode;
|
||||
stack?: string;
|
||||
});
|
||||
static codeToStatus(code: ActionErrorCode): number;
|
||||
static statusToCode(status: number): ActionErrorCode;
|
||||
static fromJson(body: any): ActionError<ErrorInferenceObject>;
|
||||
}
|
||||
export declare function isActionError(error?: unknown): error is ActionError;
|
||||
export declare function isInputError<T extends ErrorInferenceObject>(error?: ActionError<T>): error is ActionInputError<T>;
|
||||
export declare function isInputError(error?: unknown): error is ActionInputError<ErrorInferenceObject>;
|
||||
export type SafeResult<TInput extends ErrorInferenceObject, TOutput> = {
|
||||
data: TOutput;
|
||||
error: undefined;
|
||||
} | {
|
||||
data: undefined;
|
||||
error: ActionError<TInput>;
|
||||
};
|
||||
export declare class ActionInputError<T extends ErrorInferenceObject> extends ActionError {
|
||||
type: string;
|
||||
issues: z.ZodIssue[];
|
||||
fields: z.ZodError<T>['formErrors']['fieldErrors'];
|
||||
constructor(issues: z.ZodIssue[]);
|
||||
}
|
||||
export declare function callSafely<TOutput>(handler: () => MaybePromise<TOutput>): Promise<SafeResult<z.ZodType, TOutput>>;
|
||||
export declare function getActionQueryString(name: string): string;
|
||||
export type SerializedActionResult = {
|
||||
type: 'data';
|
||||
contentType: 'application/json+devalue';
|
||||
status: 200;
|
||||
body: string;
|
||||
} | {
|
||||
type: 'error';
|
||||
contentType: 'application/json';
|
||||
status: number;
|
||||
body: string;
|
||||
} | {
|
||||
type: 'empty';
|
||||
status: 204;
|
||||
};
|
||||
export declare function serializeActionResult(res: SafeResult<any, any>): SerializedActionResult;
|
||||
export declare function deserializeActionResult(res: SerializedActionResult): SafeResult<any, any>;
|
||||
export declare function astroCalledServerError(): AstroError;
|
||||
296
node_modules/astro/dist/actions/runtime/shared.js
generated
vendored
Normal file
296
node_modules/astro/dist/actions/runtime/shared.js
generated
vendored
Normal file
@@ -0,0 +1,296 @@
|
||||
import { parse as devalueParse, stringify as devalueStringify } from "devalue";
|
||||
import { REDIRECT_STATUS_CODES } from "../../core/constants.js";
|
||||
import { AstroError } from "../../core/errors/errors.js";
|
||||
import {
|
||||
ActionCalledFromServerError,
|
||||
ActionsReturnedInvalidDataError
|
||||
} from "../../core/errors/errors-data.js";
|
||||
import { appendForwardSlash as _appendForwardSlash } from "../../core/path.js";
|
||||
import { ACTION_QUERY_PARAMS as _ACTION_QUERY_PARAMS } from "../consts.js";
|
||||
const ACTION_QUERY_PARAMS = _ACTION_QUERY_PARAMS;
|
||||
const appendForwardSlash = _appendForwardSlash;
|
||||
const ACTION_ERROR_CODES = [
|
||||
"BAD_REQUEST",
|
||||
"UNAUTHORIZED",
|
||||
"PAYMENT_REQUIRED",
|
||||
"FORBIDDEN",
|
||||
"NOT_FOUND",
|
||||
"METHOD_NOT_ALLOWED",
|
||||
"NOT_ACCEPTABLE",
|
||||
"PROXY_AUTHENTICATION_REQUIRED",
|
||||
"REQUEST_TIMEOUT",
|
||||
"CONFLICT",
|
||||
"GONE",
|
||||
"LENGTH_REQUIRED",
|
||||
"PRECONDITION_FAILED",
|
||||
"CONTENT_TOO_LARGE",
|
||||
"URI_TOO_LONG",
|
||||
"UNSUPPORTED_MEDIA_TYPE",
|
||||
"RANGE_NOT_SATISFIABLE",
|
||||
"EXPECTATION_FAILED",
|
||||
"MISDIRECTED_REQUEST",
|
||||
"UNPROCESSABLE_CONTENT",
|
||||
"LOCKED",
|
||||
"FAILED_DEPENDENCY",
|
||||
"TOO_EARLY",
|
||||
"UPGRADE_REQUIRED",
|
||||
"PRECONDITION_REQUIRED",
|
||||
"TOO_MANY_REQUESTS",
|
||||
"REQUEST_HEADER_FIELDS_TOO_LARGE",
|
||||
"UNAVAILABLE_FOR_LEGAL_REASONS",
|
||||
"INTERNAL_SERVER_ERROR",
|
||||
"NOT_IMPLEMENTED",
|
||||
"BAD_GATEWAY",
|
||||
"SERVICE_UNAVAILABLE",
|
||||
"GATEWAY_TIMEOUT",
|
||||
"HTTP_VERSION_NOT_SUPPORTED",
|
||||
"VARIANT_ALSO_NEGOTIATES",
|
||||
"INSUFFICIENT_STORAGE",
|
||||
"LOOP_DETECTED",
|
||||
"NETWORK_AUTHENTICATION_REQUIRED"
|
||||
];
|
||||
const codeToStatusMap = {
|
||||
// Implemented from IANA HTTP Status Code Registry
|
||||
// https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
|
||||
BAD_REQUEST: 400,
|
||||
UNAUTHORIZED: 401,
|
||||
PAYMENT_REQUIRED: 402,
|
||||
FORBIDDEN: 403,
|
||||
NOT_FOUND: 404,
|
||||
METHOD_NOT_ALLOWED: 405,
|
||||
NOT_ACCEPTABLE: 406,
|
||||
PROXY_AUTHENTICATION_REQUIRED: 407,
|
||||
REQUEST_TIMEOUT: 408,
|
||||
CONFLICT: 409,
|
||||
GONE: 410,
|
||||
LENGTH_REQUIRED: 411,
|
||||
PRECONDITION_FAILED: 412,
|
||||
CONTENT_TOO_LARGE: 413,
|
||||
URI_TOO_LONG: 414,
|
||||
UNSUPPORTED_MEDIA_TYPE: 415,
|
||||
RANGE_NOT_SATISFIABLE: 416,
|
||||
EXPECTATION_FAILED: 417,
|
||||
MISDIRECTED_REQUEST: 421,
|
||||
UNPROCESSABLE_CONTENT: 422,
|
||||
LOCKED: 423,
|
||||
FAILED_DEPENDENCY: 424,
|
||||
TOO_EARLY: 425,
|
||||
UPGRADE_REQUIRED: 426,
|
||||
PRECONDITION_REQUIRED: 428,
|
||||
TOO_MANY_REQUESTS: 429,
|
||||
REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
|
||||
UNAVAILABLE_FOR_LEGAL_REASONS: 451,
|
||||
INTERNAL_SERVER_ERROR: 500,
|
||||
NOT_IMPLEMENTED: 501,
|
||||
BAD_GATEWAY: 502,
|
||||
SERVICE_UNAVAILABLE: 503,
|
||||
GATEWAY_TIMEOUT: 504,
|
||||
HTTP_VERSION_NOT_SUPPORTED: 505,
|
||||
VARIANT_ALSO_NEGOTIATES: 506,
|
||||
INSUFFICIENT_STORAGE: 507,
|
||||
LOOP_DETECTED: 508,
|
||||
NETWORK_AUTHENTICATION_REQUIRED: 511
|
||||
};
|
||||
const statusToCodeMap = Object.entries(codeToStatusMap).reduce(
|
||||
// reverse the key-value pairs
|
||||
(acc, [key, value]) => ({ ...acc, [value]: key }),
|
||||
{}
|
||||
);
|
||||
class ActionError extends Error {
|
||||
type = "AstroActionError";
|
||||
code = "INTERNAL_SERVER_ERROR";
|
||||
status = 500;
|
||||
constructor(params) {
|
||||
super(params.message);
|
||||
this.code = params.code;
|
||||
this.status = ActionError.codeToStatus(params.code);
|
||||
if (params.stack) {
|
||||
this.stack = params.stack;
|
||||
}
|
||||
}
|
||||
static codeToStatus(code) {
|
||||
return codeToStatusMap[code];
|
||||
}
|
||||
static statusToCode(status) {
|
||||
return statusToCodeMap[status] ?? "INTERNAL_SERVER_ERROR";
|
||||
}
|
||||
static fromJson(body) {
|
||||
if (isInputError(body)) {
|
||||
return new ActionInputError(body.issues);
|
||||
}
|
||||
if (isActionError(body)) {
|
||||
return new ActionError(body);
|
||||
}
|
||||
return new ActionError({
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
});
|
||||
}
|
||||
}
|
||||
function isActionError(error) {
|
||||
return typeof error === "object" && error != null && "type" in error && error.type === "AstroActionError";
|
||||
}
|
||||
function isInputError(error) {
|
||||
return typeof error === "object" && error != null && "type" in error && error.type === "AstroActionInputError" && "issues" in error && Array.isArray(error.issues);
|
||||
}
|
||||
class ActionInputError extends ActionError {
|
||||
type = "AstroActionInputError";
|
||||
// We don't expose all ZodError properties.
|
||||
// Not all properties will serialize from server to client,
|
||||
// and we don't want to import the full ZodError object into the client.
|
||||
issues;
|
||||
fields;
|
||||
constructor(issues) {
|
||||
super({
|
||||
message: `Failed to validate: ${JSON.stringify(issues, null, 2)}`,
|
||||
code: "BAD_REQUEST"
|
||||
});
|
||||
this.issues = issues;
|
||||
this.fields = {};
|
||||
for (const issue of issues) {
|
||||
if (issue.path.length > 0) {
|
||||
const key = issue.path[0].toString();
|
||||
this.fields[key] ??= [];
|
||||
this.fields[key]?.push(issue.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
async function callSafely(handler) {
|
||||
try {
|
||||
const data = await handler();
|
||||
return { data, error: void 0 };
|
||||
} catch (e) {
|
||||
if (e instanceof ActionError) {
|
||||
return { data: void 0, error: e };
|
||||
}
|
||||
return {
|
||||
data: void 0,
|
||||
error: new ActionError({
|
||||
message: e instanceof Error ? e.message : "Unknown error",
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
})
|
||||
};
|
||||
}
|
||||
}
|
||||
function getActionQueryString(name) {
|
||||
const searchParams = new URLSearchParams({ [_ACTION_QUERY_PARAMS.actionName]: name });
|
||||
return `?${searchParams.toString()}`;
|
||||
}
|
||||
function serializeActionResult(res) {
|
||||
if (res.error) {
|
||||
if (import.meta.env?.DEV) {
|
||||
actionResultErrorStack.set(res.error.stack);
|
||||
}
|
||||
let body2;
|
||||
if (res.error instanceof ActionInputError) {
|
||||
body2 = {
|
||||
type: res.error.type,
|
||||
issues: res.error.issues,
|
||||
fields: res.error.fields
|
||||
};
|
||||
} else {
|
||||
body2 = {
|
||||
...res.error,
|
||||
message: res.error.message
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "error",
|
||||
status: res.error.status,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify(body2)
|
||||
};
|
||||
}
|
||||
if (res.data === void 0) {
|
||||
return {
|
||||
type: "empty",
|
||||
status: 204
|
||||
};
|
||||
}
|
||||
let body;
|
||||
try {
|
||||
body = devalueStringify(res.data, {
|
||||
// Add support for URL objects
|
||||
URL: (value) => value instanceof URL && value.href
|
||||
});
|
||||
} catch (e) {
|
||||
let hint = ActionsReturnedInvalidDataError.hint;
|
||||
if (res.data instanceof Response) {
|
||||
hint = REDIRECT_STATUS_CODES.includes(res.data.status) ? "If you need to redirect when the action succeeds, trigger a redirect where the action is called. See the Actions guide for server and client redirect examples: https://docs.astro.build/en/guides/actions." : "If you need to return a Response object, try using a server endpoint instead. See https://docs.astro.build/en/guides/endpoints/#server-endpoints-api-routes";
|
||||
}
|
||||
throw new AstroError({
|
||||
...ActionsReturnedInvalidDataError,
|
||||
message: ActionsReturnedInvalidDataError.message(String(e)),
|
||||
hint
|
||||
});
|
||||
}
|
||||
return {
|
||||
type: "data",
|
||||
status: 200,
|
||||
contentType: "application/json+devalue",
|
||||
body
|
||||
};
|
||||
}
|
||||
function deserializeActionResult(res) {
|
||||
if (res.type === "error") {
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(res.body);
|
||||
} catch {
|
||||
return {
|
||||
data: void 0,
|
||||
error: new ActionError({
|
||||
message: res.body,
|
||||
code: "INTERNAL_SERVER_ERROR"
|
||||
})
|
||||
};
|
||||
}
|
||||
if (import.meta.env?.PROD) {
|
||||
return { error: ActionError.fromJson(json), data: void 0 };
|
||||
} else {
|
||||
const error = ActionError.fromJson(json);
|
||||
error.stack = actionResultErrorStack.get();
|
||||
return {
|
||||
error,
|
||||
data: void 0
|
||||
};
|
||||
}
|
||||
}
|
||||
if (res.type === "empty") {
|
||||
return { data: void 0, error: void 0 };
|
||||
}
|
||||
return {
|
||||
data: devalueParse(res.body, {
|
||||
URL: (href) => new URL(href)
|
||||
}),
|
||||
error: void 0
|
||||
};
|
||||
}
|
||||
const actionResultErrorStack = /* @__PURE__ */ function actionResultErrorStackFn() {
|
||||
let errorStack;
|
||||
return {
|
||||
set(stack) {
|
||||
errorStack = stack;
|
||||
},
|
||||
get() {
|
||||
return errorStack;
|
||||
}
|
||||
};
|
||||
}();
|
||||
function astroCalledServerError() {
|
||||
return new AstroError(ActionCalledFromServerError);
|
||||
}
|
||||
export {
|
||||
ACTION_ERROR_CODES,
|
||||
ACTION_QUERY_PARAMS,
|
||||
ActionError,
|
||||
ActionInputError,
|
||||
appendForwardSlash,
|
||||
astroCalledServerError,
|
||||
callSafely,
|
||||
deserializeActionResult,
|
||||
getActionQueryString,
|
||||
isActionError,
|
||||
isInputError,
|
||||
serializeActionResult
|
||||
};
|
||||
31
node_modules/astro/dist/actions/runtime/utils.d.ts
generated
vendored
Normal file
31
node_modules/astro/dist/actions/runtime/utils.d.ts
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { APIContext, AstroSharedContext } from '../../types/public/context.js';
|
||||
import type { SerializedActionResult } from './shared.js';
|
||||
export type ActionPayload = {
|
||||
actionResult: SerializedActionResult;
|
||||
actionName: string;
|
||||
};
|
||||
export type Locals = {
|
||||
_actionPayload: ActionPayload;
|
||||
};
|
||||
export declare const ACTION_API_CONTEXT_SYMBOL: unique symbol;
|
||||
export declare const formContentTypes: string[];
|
||||
export declare function hasContentType(contentType: string, expected: string[]): boolean;
|
||||
export type ActionAPIContext = Pick<APIContext, 'rewrite' | 'request' | 'url' | 'isPrerendered' | 'locals' | 'clientAddress' | 'cookies' | 'currentLocale' | 'generator' | 'routePattern' | 'site' | 'params' | 'preferredLocale' | 'preferredLocaleList' | 'originPathname' | 'session' | 'csp'> & {
|
||||
/**
|
||||
* @deprecated
|
||||
* The use of `rewrite` in Actions is deprecated
|
||||
*/
|
||||
rewrite: AstroSharedContext['rewrite'];
|
||||
};
|
||||
export type MaybePromise<T> = T | Promise<T>;
|
||||
/**
|
||||
* Used to preserve the input schema type in the error object.
|
||||
* This allows for type inference on the `fields` property
|
||||
* when type narrowed to an `ActionInputError`.
|
||||
*
|
||||
* Example: Action has an input schema of `{ name: z.string() }`.
|
||||
* When calling the action and checking `isInputError(result.error)`,
|
||||
* `result.error.fields` will be typed with the `name` field.
|
||||
*/
|
||||
export type ErrorInferenceObject = Record<string, any>;
|
||||
export declare function isActionAPIContext(ctx: ActionAPIContext): boolean;
|
||||
16
node_modules/astro/dist/actions/runtime/utils.js
generated
vendored
Normal file
16
node_modules/astro/dist/actions/runtime/utils.js
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
const ACTION_API_CONTEXT_SYMBOL = Symbol.for("astro.actionAPIContext");
|
||||
const formContentTypes = ["application/x-www-form-urlencoded", "multipart/form-data"];
|
||||
function hasContentType(contentType, expected) {
|
||||
const type = contentType.split(";")[0].toLowerCase();
|
||||
return expected.some((t) => type === t);
|
||||
}
|
||||
function isActionAPIContext(ctx) {
|
||||
const symbol = Reflect.get(ctx, ACTION_API_CONTEXT_SYMBOL);
|
||||
return symbol === true;
|
||||
}
|
||||
export {
|
||||
ACTION_API_CONTEXT_SYMBOL,
|
||||
formContentTypes,
|
||||
hasContentType,
|
||||
isActionAPIContext
|
||||
};
|
||||
4
node_modules/astro/dist/actions/runtime/virtual.d.ts
generated
vendored
Normal file
4
node_modules/astro/dist/actions/runtime/virtual.d.ts
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
import type { ActionClient } from './server.js';
|
||||
export * from 'virtual:astro:actions/runtime';
|
||||
export declare function getActionPath(action: ActionClient<any, any, any>): string;
|
||||
export declare const actions: Record<string | symbol, any>;
|
||||
127
node_modules/astro/dist/actions/runtime/virtual.js
generated
vendored
Normal file
127
node_modules/astro/dist/actions/runtime/virtual.js
generated
vendored
Normal file
@@ -0,0 +1,127 @@
|
||||
import { shouldAppendTrailingSlash } from "virtual:astro:actions/options";
|
||||
import { internalFetchHeaders } from "virtual:astro:adapter-config/client";
|
||||
import {
|
||||
ACTION_QUERY_PARAMS,
|
||||
ActionError,
|
||||
appendForwardSlash,
|
||||
astroCalledServerError,
|
||||
deserializeActionResult,
|
||||
getActionQueryString
|
||||
} from "./shared.js";
|
||||
export * from "virtual:astro:actions/runtime";
|
||||
const apiContextRoutesSymbol = Symbol.for("context.routes");
|
||||
const ENCODED_DOT = "%2E";
|
||||
function toActionProxy(actionCallback = {}, aggregatedPath = "") {
|
||||
return new Proxy(actionCallback, {
|
||||
get(target, objKey) {
|
||||
if (target.hasOwnProperty(objKey) || typeof objKey === "symbol") {
|
||||
return target[objKey];
|
||||
}
|
||||
const path = aggregatedPath + encodeURIComponent(objKey.toString()).replaceAll(".", ENCODED_DOT);
|
||||
function action(param) {
|
||||
return handleAction(param, path, this);
|
||||
}
|
||||
Object.assign(action, {
|
||||
queryString: getActionQueryString(path),
|
||||
toString: () => action.queryString,
|
||||
// redefine prototype methods as the object's own property, not the prototype's
|
||||
bind: action.bind,
|
||||
valueOf: () => action.valueOf,
|
||||
// Progressive enhancement info for React.
|
||||
$$FORM_ACTION: function() {
|
||||
const searchParams = new URLSearchParams(action.toString());
|
||||
return {
|
||||
method: "POST",
|
||||
// `name` creates a hidden input.
|
||||
// It's unused by Astro, but we can't turn this off.
|
||||
// At least use a name that won't conflict with a user's formData.
|
||||
name: "_astroAction",
|
||||
action: "?" + searchParams.toString()
|
||||
};
|
||||
},
|
||||
// Note: `orThrow` does not have progressive enhancement info.
|
||||
// If you want to throw exceptions,
|
||||
// you must handle those exceptions with client JS.
|
||||
async orThrow(param) {
|
||||
const { data, error } = await handleAction(param, path, this);
|
||||
if (error) throw error;
|
||||
return data;
|
||||
}
|
||||
});
|
||||
return toActionProxy(action, path + ".");
|
||||
}
|
||||
});
|
||||
}
|
||||
function _getActionPath(toString) {
|
||||
let path = `${import.meta.env.BASE_URL.replace(/\/$/, "")}/_actions/${new URLSearchParams(toString()).get(ACTION_QUERY_PARAMS.actionName)}`;
|
||||
if (shouldAppendTrailingSlash) {
|
||||
path = appendForwardSlash(path);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
function getActionPath(action) {
|
||||
return _getActionPath(action.toString);
|
||||
}
|
||||
async function handleAction(param, path, context) {
|
||||
if (import.meta.env.SSR && context) {
|
||||
const pipeline = Reflect.get(context, apiContextRoutesSymbol);
|
||||
if (!pipeline) {
|
||||
throw astroCalledServerError();
|
||||
}
|
||||
const action = await pipeline.getAction(path);
|
||||
if (!action) throw new Error(`Action not found: ${path}`);
|
||||
return action.bind(context)(param);
|
||||
}
|
||||
const headers = new Headers();
|
||||
headers.set("Accept", "application/json");
|
||||
for (const [key, value] of Object.entries(internalFetchHeaders)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
let body = param;
|
||||
if (!(body instanceof FormData)) {
|
||||
try {
|
||||
body = JSON.stringify(param);
|
||||
} catch (e) {
|
||||
throw new ActionError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Failed to serialize request body to JSON. Full error: ${e.message}`
|
||||
});
|
||||
}
|
||||
if (body) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
} else {
|
||||
headers.set("Content-Length", "0");
|
||||
}
|
||||
}
|
||||
const rawResult = await fetch(
|
||||
_getActionPath(() => getActionQueryString(path)),
|
||||
{
|
||||
method: "POST",
|
||||
body,
|
||||
headers
|
||||
}
|
||||
);
|
||||
if (rawResult.status === 204) {
|
||||
return deserializeActionResult({ type: "empty", status: 204 });
|
||||
}
|
||||
const bodyText = await rawResult.text();
|
||||
if (rawResult.ok) {
|
||||
return deserializeActionResult({
|
||||
type: "data",
|
||||
body: bodyText,
|
||||
status: 200,
|
||||
contentType: "application/json+devalue"
|
||||
});
|
||||
}
|
||||
return deserializeActionResult({
|
||||
type: "error",
|
||||
body: bodyText,
|
||||
status: rawResult.status,
|
||||
contentType: "application/json"
|
||||
});
|
||||
}
|
||||
const actions = toActionProxy();
|
||||
export {
|
||||
actions,
|
||||
getActionPath
|
||||
};
|
||||
Reference in New Issue
Block a user