init commit

This commit is contained in:
Carlos
2026-02-21 10:33:18 +01:00
parent c863a943ed
commit 9d955bf338
9512 changed files with 2015317 additions and 1305 deletions

View File

@@ -0,0 +1,4 @@
import type { ReadStream } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
export declare function setHeaderForResponse(res: ServerResponse, name: string, value: string | number): void;
export declare function send(req: IncomingMessage, res: ServerResponse, bufferOtStream: ReadStream | string | Buffer, byteLength: number): void;

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setHeaderForResponse = setHeaderForResponse;
exports.send = send;
function setHeaderForResponse(res, name, value) {
res.setHeader(name, typeof value === 'number' ? String(value) : value);
}
function send(req, res, bufferOtStream, byteLength) {
if (typeof bufferOtStream === 'string' || Buffer.isBuffer(bufferOtStream)) {
res.end(bufferOtStream);
return;
}
setHeaderForResponse(res, 'Content-Length', byteLength);
if (req.method === 'HEAD') {
res.end();
return;
}
bufferOtStream.pipe(res);
}

View File

@@ -0,0 +1,7 @@
import type { DevMiddlewareContext } from './types';
type PublicPath = {
outputPath: string;
publicPath: string;
};
export declare function getPaths(context: DevMiddlewareContext): PublicPath[];
export {};

View File

@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPaths = getPaths;
function getPaths(context) {
const { stats } = context;
const publicPaths = [];
if (!stats) {
return publicPaths;
}
const { compilation } = stats;
// The `output.path` is always present and always absolute
const outputPath = compilation.getPath(compilation.outputOptions.path || '');
const publicPath = compilation.outputOptions.publicPath
? compilation.getPath(compilation.outputOptions.publicPath)
: '';
publicPaths.push({ outputPath, publicPath });
return publicPaths;
}

View File

@@ -0,0 +1,4 @@
import type { webpack } from '@remotion/bundler';
import type { LogLevel } from '@remotion/renderer';
import type { MiddleWare } from './middleware';
export declare const wdm: (compiler: webpack.Compiler, logLevel: LogLevel) => MiddleWare;

View File

@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wdm = void 0;
const middleware_1 = require("./middleware");
const setup_hooks_1 = require("./setup-hooks");
const setup_output_filesystem_1 = require("./setup-output-filesystem");
const wdm = (compiler, logLevel) => {
const context = {
state: false,
stats: undefined,
callbacks: [],
compiler,
logger: compiler.getInfrastructureLogger('remotion'),
outputFileSystem: undefined,
};
(0, setup_hooks_1.setupHooks)(context, logLevel);
(0, setup_output_filesystem_1.setupOutputFileSystem)(context);
const errorHandler = (error) => {
if (error) {
context.logger.error(error);
}
};
const watchOptions = context.compiler.options.watchOptions || {};
context.compiler.watch(watchOptions, errorHandler);
return (0, middleware_1.middleware)(context);
};
exports.wdm = wdm;

View File

@@ -0,0 +1,8 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { DevMiddlewareContext } from './types';
export declare function getValueContentRangeHeader(type: string, size: number, range?: {
start: number;
end: number;
}): string;
export type MiddleWare = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
export declare function middleware(context: DevMiddlewareContext): (req: IncomingMessage, res: ServerResponse, next: () => void) => void;

View File

@@ -0,0 +1,219 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getValueContentRangeHeader = getValueContentRangeHeader;
exports.middleware = middleware;
const renderer_1 = require("@remotion/renderer");
const node_path_1 = __importDefault(require("node:path"));
const node_querystring_1 = __importDefault(require("node:querystring"));
const node_url_1 = require("node:url");
const compatible_api_1 = require("./compatible-api");
const get_paths_1 = require("./get-paths");
const range_parser_1 = require("./range-parser");
const ready_1 = require("./ready");
const cacheStore = new WeakMap();
const mem = (fn, { cache = new Map() } = {}) => {
const memoized = (...arguments_) => {
const [key] = arguments_;
const cacheItem = cache.get(key);
if (cacheItem) {
return cacheItem.data;
}
const result = fn.apply(this, arguments_);
cache.set(key, {
data: result,
});
return result;
};
cacheStore.set(memoized, cache);
return memoized;
};
const memoizedParse = mem(node_url_1.parse);
function getFilenameFromUrl(context, url) {
var _a, _b;
const paths = (0, get_paths_1.getPaths)(context);
let foundFilename;
let urlObject;
try {
// The `url` property of the `request` is contains only `pathname`, `search` and `hash`
urlObject = memoizedParse(url, false, true);
}
catch (_c) {
return;
}
for (const { publicPath, outputPath } of paths) {
let filename;
let publicPathObject;
try {
publicPathObject = memoizedParse(publicPath !== 'auto' && publicPath ? publicPath : '/', false, true);
}
catch (_d) {
continue;
}
if ((_a = urlObject.pathname) === null || _a === void 0 ? void 0 : _a.startsWith(publicPathObject.pathname)) {
filename = outputPath;
// Strip the `pathname` property from the `publicPath` option from the start of requested url
// `/complex/foo.js` => `foo.js`
const pathname = urlObject.pathname.substr(publicPathObject.pathname.length);
if (pathname) {
filename = node_path_1.default.join(outputPath, node_querystring_1.default.unescape(pathname));
}
if (!context.outputFileSystem) {
continue;
}
try {
let fsStats = (_b = context.outputFileSystem) === null || _b === void 0 ? void 0 : _b.statSync(filename);
if (fsStats.isFile()) {
foundFilename = filename;
break;
}
else if (fsStats.isDirectory()) {
const indexValue = 'index.html';
filename = node_path_1.default.join(filename, indexValue);
try {
fsStats = context.outputFileSystem.statSync(filename);
}
catch (_e) {
continue;
}
if (fsStats.isFile()) {
foundFilename = filename;
break;
}
}
}
catch (_f) {
continue;
}
}
}
return foundFilename;
}
function getValueContentRangeHeader(type, size, range) {
return `${type} ${range ? `${range.start}-${range.end}` : '*'}/${size}`;
}
function createHtmlDocument(title, body) {
return (`${'<!DOCTYPE html>\n' +
'<html lang="en">\n' +
'<head>\n' +
'<meta charset="utf-8">\n' +
'<title>'}${title}</title>\n` +
`</head>\n` +
`<body>\n` +
`<pre>${body}</pre>\n` +
`</body>\n` +
`</html>\n`);
}
const BYTES_RANGE_REGEXP = /^ *bytes/i;
function middleware(context) {
return function (req, res, next) {
const acceptedMethods = ['GET', 'HEAD'];
if (req.method && !acceptedMethods.includes(req.method)) {
goNext();
return;
}
(0, ready_1.ready)(context, processRequest);
function goNext() {
return next();
}
async function processRequest() {
var _a;
const filename = getFilenameFromUrl(context, req.url);
if (!filename) {
goNext();
return;
}
/**
* @type {{key: string, value: string | number}[]}
*/
if (!res.getHeader('Content-Type')) {
// content-type name(like application/javascript; charset=utf-8) or false
const contentType = renderer_1.RenderInternals.mimeContentType(node_path_1.default.extname(filename));
// Only set content-type header if media type is known
// https://tools.ietf.org/html/rfc7231#section-3.1.1.5
if (contentType) {
(0, compatible_api_1.setHeaderForResponse)(res, 'Content-Type', contentType);
}
}
if (!res.getHeader('Accept-Ranges')) {
res.setHeader('Accept-Ranges', 'bytes');
(0, compatible_api_1.setHeaderForResponse)(res, 'Accept-Ranges', 'bytes');
}
const rangeHeader = req.headers.range;
let start;
let end;
if (rangeHeader &&
BYTES_RANGE_REGEXP.test(rangeHeader) &&
context.outputFileSystem) {
const size = await new Promise((resolve) => {
var _a;
(_a = context.outputFileSystem) === null || _a === void 0 ? void 0 : _a.lstat(filename, (error, stats) => {
var _a;
if (error) {
context.logger.error(error);
return;
}
resolve((_a = stats === null || stats === void 0 ? void 0 : stats.size) !== null && _a !== void 0 ? _a : 0);
});
});
const parsedRanges = (0, range_parser_1.parseRange)(size, rangeHeader);
if (parsedRanges === -1) {
const message = "Unsatisfiable range for 'Range' header.";
context.logger.error(message);
const existingHeaders = res.getHeaderNames();
for (const header of existingHeaders) {
res.removeHeader(header);
}
res.statusCode = 416;
(0, compatible_api_1.setHeaderForResponse)(res, 'Content-Range', getValueContentRangeHeader('bytes', size));
(0, compatible_api_1.setHeaderForResponse)(res, 'Content-Type', 'text/html; charset=utf-8');
const document = createHtmlDocument(416, `Error: ${message}`);
const _byteLength = Buffer.byteLength(document);
(0, compatible_api_1.setHeaderForResponse)(res, 'Content-Length', Buffer.byteLength(document));
(0, compatible_api_1.send)(req, res, document, _byteLength);
return;
}
if (parsedRanges === -2) {
context.logger.error("A malformed 'Range' header was provided. A regular response will be sent for this request.");
}
else if (parsedRanges.length > 1) {
context.logger.error("A 'Range' header with multiple ranges was provided. Multiple ranges are not supported, so a regular response will be sent for this request.");
}
if (parsedRanges !== -2 && parsedRanges.length === 1) {
// Content-Range
res.statusCode = 206;
(0, compatible_api_1.setHeaderForResponse)(res, 'Content-Range', getValueContentRangeHeader('bytes', size, parsedRanges[0]));
[{ start, end }] = parsedRanges;
}
}
const isFsSupportsStream = typeof ((_a = context.outputFileSystem) === null || _a === void 0 ? void 0 : _a.createReadStream) === 'function';
let bufferOtStream;
let byteLength = 0;
try {
if (typeof start !== 'undefined' &&
typeof end !== 'undefined' &&
isFsSupportsStream &&
context.outputFileSystem) {
bufferOtStream = context.outputFileSystem.createReadStream(filename, {
start,
end,
});
byteLength = end - start + 1;
}
else if (context.outputFileSystem) {
bufferOtStream = context.outputFileSystem.readFileSync(filename);
byteLength = bufferOtStream.byteLength;
}
}
catch (_b) {
goNext();
return;
}
if (bufferOtStream) {
(0, compatible_api_1.send)(req, res, bufferOtStream, byteLength);
}
}
};
}

View File

@@ -0,0 +1,15 @@
/*!
* range-parser
* Copyright(c) 2012-2014 TJ Holowaychuk
* Copyright(c) 2015-2016 Douglas Christopher Wilson
* MIT Licensed
*/
type Range = {
start: number;
end: number;
};
type Ranges = Range[] & {
type?: string;
};
export declare function parseRange(size: number, str: string | string[]): -1 | Ranges | -2;
export {};

View File

@@ -0,0 +1,95 @@
"use strict";
/*!
* range-parser
* Copyright(c) 2012-2014 TJ Holowaychuk
* Copyright(c) 2015-2016 Douglas Christopher Wilson
* MIT Licensed
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseRange = parseRange;
function parseRange(size, str) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
const index = str.indexOf('=');
if (index === -1) {
return -2;
}
// split the range string
const arr = str.slice(index + 1).split(',');
const ranges = [];
// add ranges type
ranges.type = str.slice(0, index);
// parse all ranges
for (let i = 0; i < arr.length; i++) {
const range = arr[i].split('-');
let start = parseInt(range[0], 10);
let end = parseInt(range[1], 10);
// -nnn
if (isNaN(start)) {
start = size - end;
end = size - 1;
// nnn-
}
else if (isNaN(end)) {
end = size - 1;
}
// limit last-byte-pos to current length
if (end > size - 1) {
end = size - 1;
}
// invalid or unsatisifiable
if (isNaN(start) || isNaN(end) || start > end || start < 0) {
continue;
}
// add range
ranges.push({
start,
end,
});
}
if (ranges.length < 1) {
return -1;
}
return combineRanges(ranges);
}
function combineRanges(ranges) {
const ordered = ranges.map(mapWithIndex).sort(sortByRangeStart);
let j = 0;
for (let i = 1; i < ordered.length; i++) {
const range = ordered[i];
const current = ordered[j];
if (range.start > current.end + 1) {
// next range
ordered[++j] = range;
}
else if (range.end > current.end) {
// extend range
current.end = range.end;
current.index = Math.min(current.index, range.index);
}
}
ordered.length = j + 1;
const combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex);
combined.type = ranges.type;
return combined;
}
function mapWithIndex(range, index) {
return {
start: range.start,
end: range.end,
index,
};
}
function mapWithoutIndex(range) {
return {
start: range.start,
end: range.end,
};
}
function sortByRangeIndex(a, b) {
return a.index - b.index;
}
function sortByRangeStart(a, b) {
return a.start - b.start;
}

View File

@@ -0,0 +1,3 @@
import type { webpack } from '@remotion/bundler';
import type { DevMiddlewareContext } from './types';
export declare function ready(context: DevMiddlewareContext, callback: (stats: webpack.Stats | undefined) => undefined | Promise<void>): void;

View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ready = ready;
function ready(context, callback) {
if (context.state) {
callback(context.stats);
return;
}
context.callbacks.push(callback);
}

View File

@@ -0,0 +1,3 @@
import type { LogLevel } from '@remotion/renderer';
import type { DevMiddlewareContext } from './types';
export declare function setupHooks(context: DevMiddlewareContext, logLevel: LogLevel): void;

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupHooks = setupHooks;
const renderer_1 = require("@remotion/renderer");
const no_react_1 = require("remotion/no-react");
function setupHooks(context, logLevel) {
function invalid() {
// We are now in invalid state
context.state = false;
context.stats = undefined;
}
function done(stats) {
context.state = true;
context.stats = stats;
// Do the stuff in nextTick, because bundle may be invalidated if a change happened while compiling
process.nextTick(() => {
const { logger, state, callbacks } = context;
// Check if still in valid state
if (!state || !stats) {
return;
}
logger.log('Compilation finished');
const statsOptions = {
preset: 'errors-warnings',
colors: renderer_1.RenderInternals.isColorSupported(),
};
const printedStats = stats.toString(statsOptions);
const lines = printedStats
.split('\n')
.map((a) => a.trimEnd())
.filter(no_react_1.NoReactInternals.truthy)
.map((a) => {
if (a.startsWith('webpack compiled')) {
return `Built in ${stats.endTime - stats.startTime}ms`;
}
return a;
})
.join('\n');
if (lines) {
renderer_1.RenderInternals.Log.info({ indent: false, logLevel }, lines);
if (process.argv.includes('--test-for-server-open')) {
renderer_1.RenderInternals.Log.info({ indent: false, logLevel }, 'Yes, the server started.');
process.exit(0);
}
}
context.callbacks = [];
callbacks.forEach((callback) => {
callback(stats);
});
});
}
context.compiler.hooks.watchRun.tap('remotion', invalid);
context.compiler.hooks.invalid.tap('remotion', invalid);
context.compiler.hooks.done.tap('remotion', done);
}

View File

@@ -0,0 +1,2 @@
import type { DevMiddlewareContext } from './types';
export declare function setupOutputFileSystem(context: DevMiddlewareContext): void;

View File

@@ -0,0 +1,13 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupOutputFileSystem = setupOutputFileSystem;
const memfs_1 = __importDefault(require("memfs"));
function setupOutputFileSystem(context) {
const outputFileSystem = memfs_1.default.createFsFromVolume(new memfs_1.default.Volume());
// @ts-expect-error output file sytem
context.compiler.outputFileSystem = outputFileSystem;
context.outputFileSystem = outputFileSystem;
}

View File

@@ -0,0 +1,10 @@
import type { webpack } from '@remotion/bundler';
import type memfs from 'memfs';
export type DevMiddlewareContext = {
state: boolean;
stats: webpack.Stats | undefined;
callbacks: ((stats: webpack.Stats) => undefined | Promise<void>)[];
compiler: webpack.Compiler;
logger: ReturnType<webpack.Compiler['getInfrastructureLogger']>;
outputFileSystem: memfs.IFs | undefined;
};

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });