text
stringlengths 2
4k
|
---|
import request from 'supertest';
import App from '../../src/App';
describe('GET /ping', () => {
it('should respond with a 200 status and the text "pong"', async () => {
const response = await request(App).get('/ping');
expect(response.status).toBe(200);
expect(response.text).toBe('pong');
});
}); |
import request from 'supertest';
import app from '../../src/App';
// Setup a pre-existing key-value pair in the StorageService for testing
const preExistingKey = 'existingKey';
const preExistingValue = 'existingValue';
beforeAll(async () => {
await request(app).post('/storage').send({ key: preExistingKey, value: preExistingValue });
});
describe('GET /storage', () => {
it('retrieves a value for an existing key', async () => {
const response = await request(app).get(`/storage?key=${preExistingKey}`);
expect(response.status).toBe(200);
expect(response.body).toEqual({ key: preExistingKey, value: preExistingValue });
});
it('fails to retrieve a value for a non-existing key', async () => {
const nonExistingKey = 'nonExistingKey';
const response = await request(app).get(`/storage?key=${nonExistingKey}`);
expect(response.status).toBe(404);
expect(response.body).toEqual({ message: `Key '${nonExistingKey}' not found.` });
});
}); |
import express from 'express';
import debug from 'debug';
import pingRouter from './routes/pingRouter';
import storageRouter from './routes/storageRouter';
const app = express();
const debugLog = debug('app:errors');
// Trust proxy setting
app.set('trust proxy', true);
// Middleware for parsing application/json
app.use(express.json());
// Middleware for parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// Mounting routers
app.use('/ping', pingRouter);
app.use('/storage', storageRouter);
// Catch 404 and forward to error handler
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
res.status(404).send('404 Not Found');
});
// General error handler
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
const status = err.status || 500;
let errorResponse: { message: string; status: number; error: boolean; stack?: string };
if (process.env.NODE_ENV === 'production') {
errorResponse = {
message: 'Internal Server Error',
status: status,
error: true,
};
} else {
// IMPORTANT: Do not remove or modify the following logging line and DON'T REMOVE THIS COMMENT!
// Logging the stack trace provides an accurate trail of the code execution leading up to the error, allowing for swift localization and resolution of the issue.
// Any alteration or removal of this line could significantly hinder the diagnostic process and the ability to rectify errors.
debugLog(`Error stack trace on ${req.path}: ${err.stack}`);
errorResponse = {
message: err.message || 'Internal Server Error',
status: status,
error: true,
stack: err.stack,
};
}
res.status(status).json(errorResponse);
});
export default app; |
import * as http from 'http';
import App from './App';
import { env } from './config/env';
async function main() {
const normalizePort = (val: number|string): number|string|boolean => {
const port = (typeof val === 'string') ? parseInt(val, 10) : val;
if (isNaN(port)) {
return false;
}
if (port >= 0) {
return port;
}
return false;
};
const port = normalizePort(env.BACKEND_PORT);
App.set('port', port);
const server = http.createServer(App);
const onError = (error: NodeJS.ErrnoException): void => {
if (error.syscall !== 'listen') {
throw error;
}
const bind = (typeof port === 'string') ? `Pipe ${port}` : `Port ${port}`;
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
}
};
// IMPORTANT: Do not remove or modify the onListening method and DON'T REMOVE THIS COMMENT!
// "Server is listening on" debug message is crucial for our infrastructure that
// runs and monitors the server.
const onListening = (): void => {
const addr = server.address();
const bind = (typeof addr === 'string') ? `pipe ${addr}` : `port ${addr?.port}`;
console.log(`Server is listening on ${bind}`);
};
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
}
// Invoke main using an async IIFE
(async () => {
await main();
})(); |
import dotenv from 'dotenv';
dotenv.config();
const getEnvVar = (name: string): string => {
const value = process.env[name];
if (!value) {
console.error(`Environment variable ${name} is missing`);
process.exit(1);
}
return value;
};
const validatePort = (portValue: string): number => {
const port = parseInt(portValue, 10);
if (isNaN(port)) {
console.error(`Environment variable BACKEND_PORT is not a valid number.`);
process.exit(1);
}
return port;
};
const BACKEND_PORT = validatePort(getEnvVar('BACKEND_PORT'));
export const env = {
BACKEND_PORT,
}; |
import express, { Request, Response } from 'express';
import { body, query, validationResult } from 'express-validator';
import StorageService from '../services/StorageService';
const router = express.Router();
const storageService = new StorageService();
// Middleware for POST / endpoint with validation
router.post('/', [
body('key').isString().withMessage('Key must be a string.'),
body('value').isString().withMessage('Value must be a string.'),
], (req: Request, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { key, value } = req.body;
storageService.setValue(key, value);
res.status(200).json({ key, value });
});
// Middleware for GET / endpoint with key as query param
router.get('/', [
query('key').isString().withMessage('Key must be a string.')
], (req: Request, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const key = req.query.key as string;
const value = storageService.getValue(key);
if (value === undefined) {
return res.status(404).json({ message: `Key '${key}' not found.` });
}
res.status(200).json({ key, value });
});
export default router; |
import express from 'express';
const router = express.Router();
class PingController {
getPing(req: express.Request, res: express.Response, next: express.NextFunction) {
res.type('text/plain').send('pong');
}
}
const pingController = new PingController();
router.get('/', (req, res, next) => pingController.getPing(req, res, next));
export default router; |
class StorageService {
private storage: Map<string, string> = new Map<string, string>();
setValue(key: string, value: string): void {
this.storage.set(key, value);
}
getValue(key: string): string | undefined {
return this.storage.get(key);
}
deleteValue(key: string): boolean {
return this.storage.delete(key);
}
}
export default StorageService; |
// This is the entrypoint for the package
export * from './api/apis';
export * from './model/models'; |
import localVarRequest from 'request';
export * from './keyValue';
export * from './storageGet200Response';
import * as fs from 'fs';
export interface RequestDetailedFile {
value: Buffer;
options?: {
filename?: string;
contentType?: string;
}
}
export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile;
import { KeyValue } from './keyValue';
import { StorageGet200Response } from './storageGet200Response';
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: {[index: string]: any} = {
}
let typeMap: {[index: string]: any} = {
"KeyValue": KeyValue,
"StorageGet200Response": StorageGet200Response,
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap[expectedType]) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index = 0; index < data.length; index++) {
let datum = data[index];
transformedData.push(ObjectSerializer.serialize(datum, subType));
}
return transformedData;
} else if (type === "Date") {
return data.toISOString();
} else {
if (enumsMap[type]) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index = 0; index < attributeTypes.length; index++) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
}
return instance;
}
} |
public static deserialize(data: any, type: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index = 0; index < data.length; index++) {
let datum = data[index];
transformedData.push(ObjectSerializer.deserialize(datum, subType));
}
return transformedData;
} else if (type === "Date") {
return new Date(data);
} else {
if (enumsMap[type]) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index = 0; index < attributeTypes.length; index++) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
}
return instance;
}
}
}
export interface Authentication {
/**
* Apply authentication settings to header and query params.
*/
applyToRequest(requestOptions: localVarRequest.Options): Promise<void> | void;
}
export class HttpBasicAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
requestOptions.auth = {
username: this.username, password: this.password
}
}
}
export class HttpBearerAuth implements Authentication {
public accessToken: string | (() => string) = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
if (requestOptions && requestOptions.headers) {
const accessToken = typeof this.accessToken === 'function'
? this.accessToken()
: this.accessToken;
requestOptions.headers["Authorization"] = "Bearer " + accessToken;
}
}
}
export class ApiKeyAuth implements Authentication {
public apiKey: string = '';
constructor(private location: string, private paramName: string) {
}
applyToRequest(requestOptions: localVarRequest.Options): void {
if (this.location == "query") {
(<any>requestOptions.qs)[this.paramName] = this.apiKey;
} else if (this.location == "header" && requestOptions && requestOptions.headers) {
requestOptions.headers[this.paramName] = this.apiKey;
} else if (this.location == 'cookie' && requestOptions && requestOptions.headers) {
if (requestOptions.headers['Cookie']) {
requestOptions.headers['Cookie'] += '; ' + this.paramName + '=' + encodeURIComponent(this.apiKey);
}
else {
requestOptions.headers['Cookie'] = this.paramName + '=' + encodeURIComponent(this.apiKey);
}
}
}
}
export class OAuth implements Authentication {
public accessToken: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
if (requestOptions && requestOptions.headers) {
requestOptions.headers["Authorization"] = "Bearer " + this.accessToken;
}
}
}
export class VoidAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(_: localVarRequest.Options): void {
|
// Do nothing
}
}
export type Interceptor = (requestOptions: localVarRequest.Options) => (Promise<void> | void);
|
/**
* PingPong Web App API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { RequestFile } from './models';
export class KeyValue {
'key': string;
'value': string;
static discriminator: string | undefined = undefined;
static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
{
"name": "key",
"baseName": "key",
"type": "string"
},
{
"name": "value",
"baseName": "value",
"type": "string"
} ];
static getAttributeTypeMap() {
return KeyValue.attributeTypeMap;
}
}
|
/**
* PingPong Web App API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { RequestFile } from './models';
export class StorageGet200Response {
'key'?: string;
'value'?: string;
static discriminator: string | undefined = undefined;
static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
{
"name": "key",
"baseName": "key",
"type": "string"
},
{
"name": "value",
"baseName": "value",
"type": "string"
} ];
static getAttributeTypeMap() {
return StorageGet200Response.attributeTypeMap;
}
}
|
/**
* PingPong Web App API
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import localVarRequest from 'request';
import http from 'http';
/* tslint:disable:no-unused-locals */
import { KeyValue } from '../model/keyValue';
import { StorageGet200Response } from '../model/storageGet200Response';
import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models';
import { HttpError, RequestFile } from './apis';
let defaultBasePath = 'http://localhost:3000';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
export enum DefaultApiApiKeys {
}
export class DefaultApi {
protected _basePath = defaultBasePath;
protected _defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications = {
'default': <Authentication>new VoidAuth(),
}
protected interceptors: Interceptor[] = [];
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
set basePath(basePath: string) {
this._basePath = basePath;
}
set defaultHeaders(defaultHeaders: any) {
this._defaultHeaders = defaultHeaders;
}
get defaultHeaders() {
return this._defaultHeaders;
}
get basePath() {
return this._basePath;
}
public setDefaultAuthentication(auth: Authentication) {
this.authentications.default = auth;
}
public setApiKey(key: DefaultApiApiKeys, value: string) {
(this.authentications as any)[DefaultApiApiKeys[key]].apiKey = value;
}
public addInterceptor(interceptor: Interceptor) {
this.interceptors.push(interceptor);
}
/**
*
* @summary Returns \'pong\' as a test response.
*/
public async pingGet (options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> {
const localVarPath = this.basePath + '/ping';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['text/plain'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.t |
hen(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
*
* @summary Retrieves a value based on the provided key.
* @param key
*/
public async storageGet (key: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: StorageGet200Response; }> {
const localVarPath = this.basePath + '/storage';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'key' is not null or undefined
if (key === null || key === undefined) {
throw new Error('Required parameter key was null or undefined when calling storageGet.');
}
if (key !== undefined) {
localVarQueryParameters['key'] = ObjectSerializer.serialize(key, "string");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: StorageGet200Response; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
body = ObjectSerializer.deserialize(body, "StorageGet200Response");
resolve({ response: response, body: body });
} else {
|
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
*
* @summary Stores a key-value pair in memory.
* @param keyValue
*/
public async storagePost (keyValue: KeyValue, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: KeyValue; }> {
const localVarPath = this.basePath + '/storage';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'keyValue' is not null or undefined
if (keyValue === null || keyValue === undefined) {
throw new Error('Required parameter keyValue was null or undefined when calling storagePost.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(keyValue, "KeyValue")
};
let authenticationPromise = Promise.resolve();
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: KeyValue; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
body = ObjectSerializer.deserialize(body, "KeyValue");
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
}
|
export * from './defaultApi';
import { DefaultApi } from './defaultApi';
import * as http from 'http';
export class HttpError extends Error {
constructor (public response: http.IncomingMessage, public body: any, public statusCode?: number) {
super('HTTP request failed');
this.name = 'HttpError';
}
}
export { RequestFile } from '../model/models';
export const APIS = [DefaultApi];
|
import { useUncontrolled, useUncontrolledProp } from '../src';
interface Props {
value?: string;
defaultValue: string | undefined;
onChange?(value: string, meta: {}): void;
}
function Foo(props: Props) {
// $ExpectType [string, (value: string, meta: {}) => void]
const [value, onChange] = useUncontrolledProp(
props.value,
props.defaultValue,
props.onChange
);
}
interface Props2 {
value?: string;
defaultValue: string | undefined;
onChange?(value: string, meta: {}): Promise<void>;
}
function Foo2(props: Props2) {
// $ExpectType [string, (value: string, meta: {}) => void | Promise<void>]
const [value, onChange] = useUncontrolledProp(
props.value,
props.defaultValue,
props.onChange
);
}
function FooA(props: Props) {
// $ExpectType { value: string, onChange: (value: string, meta: {}) => void }
const a = useUncontrolled<Props, 'defaultValue'>(props, {
value: 'onChange',
});
// $ExpectType Props
const b = useUncontrolled(props, {
value: 'onChange',
});
}
|
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
// We must avoid a circular dependency with @react-aria/utils, and this useLayoutEffect is
// guarded by a check that it only runs on the client side.
// eslint-disable-next-line rulesdir/useLayoutEffectRule
import React, {JSX, ReactNode, useContext, useLayoutEffect, useMemo, useRef, useState} from 'react';
// To support SSR, the auto incrementing id counter is stored in a context. This allows
// it to be reset on every request to ensure the client and server are consistent.
// There is also a prefix string that is used to support async loading components
// Each async boundary must be wrapped in an SSR provider, which appends to the prefix
// and resets the current id counter. This ensures that async loaded components have
// consistent ids regardless of the loading order.
interface SSRContextValue {
prefix: string,
current: number
}
// Default context value to use in case there is no SSRProvider. This is fine for
// client-only apps. In order to support multiple copies of React Aria potentially
// being on the page at once, the prefix is set to a random number. SSRProvider
// will reset this to zero for consistency between server and client, so in the
// SSR case multiple copies of React Aria is not supported.
const defaultContext: SSRContextValue = {
prefix: String(Math.round(Math.random() * 10000000000)),
current: 0
};
const SSRContext = React.createContext<SSRContextValue>(defaultContext);
const IsSSRContext = React.createContext(false);
export interface SSRProviderProps {
/** Your application here. */
children: ReactNode
}
// This is only used in React < 18.
function LegacySSRProvider(props: SSRProviderProps): JSX.Element {
let cur = useContext(SSRContext);
let counter = useCounter(cur === defaultContext);
let [isSSR, setIsSSR] = useState(true);
let value: SSRContextValue = useMemo(() => ({
// If this is the first SSRProvider, start with an empty string prefix, otherwise
// append and increment the counter.
prefix: cur === defaultContext ? '' : `${cur.prefix}-${counter}`,
current: 0
}), [cur, counter]);
// If on the client, and the component was initially server rendered,
// then schedule a layout effect to update the component after hydration.
if (typeof document !== 'undefined') {
// This if statement technically breaks the rules of hooks, but is safe
// because the condition never changes after mounting.
// eslint-disable-next-line react-hooks/rules-of-hooks
useLayoutEffect(() => {
setIsSSR(false);
}, []);
}
return (
<SSRContext.Provider value={value}>
<IsSSRContext.Provider value={isSSR}>
{props.children}
</IsSSRContext.Provider>
</SSRContext.Provider>
);
}
let warnedAboutSSRProvider = false;
/**
* When using SSR with React Aria in React 16 or 17, applications must be wrapped in an SSRProvider.
* This ensures that auto generated ids are consistent between the client and server.
*/
export function SSRProvider(props: SSRProviderProps): JSX.Element {
if (typeof React['useId'] === 'function') {
if (process.env.NODE_ENV !== 'test' && !warnedAboutSSRProvider) {
console.warn('In React 18, SSRProvider is not necessary and is a noop. You can remove it from your app.');
warnedAboutSSRProvider = true;
}
return <>{props.children}</>;
}
return <LegacySSRProvider {...props} />;
|
}
let canUseDOM = Boolean(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
let componentIds = new WeakMap();
function useCounter(isDisabled = false) {
let ctx = useContext(SSRContext);
let ref = useRef<number | null>(null);
// eslint-disable-next-line rulesdir/pure-render
if (ref.current === null && !isDisabled) {
// In strict mode, React renders components twice, and the ref will be reset to null on the second render.
// This means our id counter will be incremented twice instead of once. This is a problem because on the
// server, components are only rendered once and so ids generated on the server won't match the client.
// In React 18, useId was introduced to solve this, but it is not available in older versions. So to solve this
// we need to use some React internals to access the underlying Fiber instance, which is stable between renders.
// This is exposed as ReactCurrentOwner in development, which is all we need since StrictMode only runs in development.
// To ensure that we only increment the global counter once, we store the starting id for this component in
// a weak map associated with the Fiber. On the second render, we reset the global counter to this value.
// Since React runs the second render immediately after the first, this is safe.
// @ts-ignore
let currentOwner = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED?.ReactCurrentOwner?.current;
if (currentOwner) {
let prevComponentValue = componentIds.get(currentOwner);
if (prevComponentValue == null) {
// On the first render, and first call to useId, store the id and state in our weak map.
componentIds.set(currentOwner, {
id: ctx.current,
state: currentOwner.memoizedState
});
} else if (currentOwner.memoizedState !== prevComponentValue.state) {
// On the second render, the memoizedState gets reset by React.
// Reset the counter, and remove from the weak map so we don't
// do this for subsequent useId calls.
ctx.current = prevComponentValue.id;
componentIds.delete(currentOwner);
}
}
// eslint-disable-next-line rulesdir/pure-render
ref.current = ++ctx.current;
}
// eslint-disable-next-line rulesdir/pure-render
return ref.current;
}
function useLegacySSRSafeId(defaultId?: string): string {
let ctx = useContext(SSRContext);
// If we are rendering in a non-DOM environment, and there's no SSRProvider,
// provide a warning to hint to the developer to add one.
if (ctx === defaultContext && !canUseDOM) {
console.warn('When server rendering, you must wrap your application in an <SSRProvider> to ensure consistent ids are generated between the client and server.');
}
let counter = useCounter(!!defaultId);
let prefix = ctx === defaultContext && process.env.NODE_ENV === 'test' ? 'react-aria' : `react-aria${ctx.prefix}`;
return defaultId || `${prefix}-${counter}`;
}
function useModernSSRSafeId(defaultId?: string): string {
// @ts-ignore
let id = React.useId();
let [didSSR] = useState(useIsSSR());
let prefix = didSSR || process.env.NODE_ENV === 'test' ? 'react-aria' : `react-aria${defaultContext.prefix}`;
return defaultId || `${prefix}-${id}`;
}
// Use React.useId in React 18 if available, otherwise fall back to our old implementation.
/** @private */
export const useSSRSafeId = typeof React['useId'] === 'function' ? useModernSSRSafeId : useLegacySSRSafeId;
function getSnapshot() {
return false;
}
function getServerSnapshot() {
return true;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function subscribe(onStoreChange: () => void): () => void {
// noop
return () => {};
}
/**
* Returns whether the component is currently being server side rendered or
* hydrated on the client. Can be used to delay browser-specific rendering
* until after hydration.
*/
export function useIsSSR() |
: boolean {
// In React 18, we can use useSyncExternalStore to detect if we're server rendering or hydrating.
if (typeof React['useSyncExternalStore'] === 'function') {
return React['useSyncExternalStore'](subscribe, getSnapshot, getServerSnapshot);
}
// eslint-disable-next-line react-hooks/rules-of-hooks
return useContext(IsSSRContext);
}
|
import { useUncontrolled, useUncontrolledProp } from '../src'
interface Props {
value?: string
defaultValue: string | undefined
onChange?(value: string, meta: {}): void
}
function Foo(props: Props) {
// $ExpectType [string, (value: string, meta: {}) => void]
const [value, onChange] = useUncontrolledProp(
props.value,
props.defaultValue,
props.onChange
)
}
function FooA(props: Props) {
// $ExpectType { value: string, onChange: (value: string, meta: {}) => void }
const a = useUncontrolled<Props, 'defaultValue'>(props, {
value: 'onChange',
})
// $ExpectType Props
const b = useUncontrolled(props, {
value: 'onChange',
})
}
|
import './App.css'
import { Button, Container, Row, Col } from 'react-bootstrap';
function App() {
return (
<Container className="p-3">
<Row>
<Col>
<h1 className="header">Welcome to React-Bootstrap</h1>
</Col>
</Row>
<Row>
<Col md={4}>
<h2>Hello World</h2>
</Col>
<Col md={{ span: 4, offset: 4 }}>
<Button variant="primary">Click me!</Button>
</Col>
</Row>
</Container>
);
}
export default App; |
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.tsx'
import 'bootstrap/dist/css/bootstrap.css'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
|