@salla.sa/base

中文文档
3.0.21发布于 2026/11/02GPL-3.0TypeScriptESM + CJS

Salla Base

原始使用文档
文档目录16 节
  1. Overview
  2. Getting Started
  3. Installation
  4. What's included?
  5. Usage
  6. Confiruration
  7. Helpers
  8. Storage
  9. Cookies
  10. Logger
  11. Events
  12. FormDataWrapper
  13. Support
  14. Contributing
  15. Credits
  16. License

Logo

Salla Core JS

Kick off your Salla JS project with this core package. It includes the main elements needed for building a JS project. On top of that, it's based on the Event-Driven Architecture.
Explore our blogs »

Report Bug · Request Feature . </Salla Developers> . Official Documentation

Table of Contents
  1. Overview
  2. Getting Started
  3. Usage
  4. Support
  5. Contributing
  6. Credits
  7. License

Overview

Salla Core JS package is based on the Event-Driven Architecture, which is a modern design approach centered on data that represents "events" (i.e., a product has been added to the cart). In event-driven programming, an event is the result of a single or multiple actions. Subscribers can listen to that event and take action after it is released by the emitter.

Getting Started

Salla Core JS uses EventEmitter2, which is an implementation of the EventEmitter module found in Node.js. It not only outperforms EventEmitter in benchmarks and is browser-compatible, but it also adds a slew of new non-breaking functionality to the EventEmitter interface.

Installation

Salla Core JS can be installed from the npm using the following commands:

npm install @salla.sa/base --save
yarn add @salla.sa/base

What's included?

A quick look at the top-level files in the Salla Core JS project:

.
├── src / helpers
├── src / config.d.ts
├── src / cookie.ts
├── src / event.js
├── src / index.ts
├── src / logger.ts
└── src / storage.js

Usage

import Salla from "@salla.sa/base"

Upon the installation, the following will be available to the developer:

Confiruration

When the JS Core project is first loaded, the initialization procedure is used to obtain the necessary configuration settings. The developer has the ability to configure the project to meet his needs.

Helpers

The JS Core project is packaged with a variety of helpful functions that may be accessed and used directly within projects.

Storage

Developers can use local storage to save and retrieve data in the browser. The data in local storage does not have an expiration date. This means that even if the tab or browser window is closed, the data will remain. Furthermore, the data is only saved locally.

Cookies

The JS Core project makes it easy to create, retrieve, and modify cookies. Name, value, and length can be limited.

Logger

The JS Core project includes a logger tool that helps in tracking the execution flow and determining why certain things occur in the JS application.

Events

The Events can be triggered by the emitter's 'emit()' method. This method causes the event to be pushed using the data that the developer has provided.

For example, the developer may create an event based on verified login by the user. Simply, the emit() method can be called with a list of parameters. These parameters state the event's action and the passed data along with it as below:

// via event name
Salla.event.emit("auth::verified",  {success:  true},  'email')

Listening to the event

After creating the event along with its list of data, the next step is to implement an appropriate listener for that event. In Salla JS Events, this can be achieved using two methods:

  • Using the event name and result directly along with an anonymized function to perform the needed action based on the event result.
// via event name
Salla.event.on('auth::verified',(response, authType)  =>  {
// lets do anything when the event emit
console.log('The customer has been verifed');
console.log(response, authType)
});
  • Adding a one time listener for the event along with an anonymized function to perform the needed action based on the event result.
// Adds a one time listener for the event.
Salla.event.once('auth::verified',(response, authType)  =>  {
// The listener is invoked only the first time
// the event is fired, after which it is removed.
console.log('The customer has been verifed');
console.log(response, authType)
})

(back to top)

FormDataWrapper

The FormDataWrapper provides a unified interface for working with both regular objects and FormData, making it easier to handle file uploads and form data in a consistent way.

Usage Examples

Example 1: Basic file handling with FormData
const formData = new FormData();
const wrapped = createWrapper(formData);

// Adding a single file
const file1 = new File(['Hello World'], 'hello.txt', { type: 'text/plain' });
wrapped.document = file1;  // Works via proxy
// OR
wrapped.setFile('document', file1);  // Explicit file method

// Getting the file back
const retrievedFile = wrapped.document;  // Returns File object
console.log(retrievedFile.name);  // 'hello.txt'
console.log(retrievedFile.size);  // 11 (bytes)
Example 2: Multiple files with the same key
const file2 = new File(['Second file'], 'second.txt', { type: 'text/plain' });
const file3 = new File(['Third file'], 'third.txt', { type: 'text/plain' });

// Setting multiple files at once (replaces existing)
wrapped.attachments = [file2, file3];

// Or append files one by one
wrapped.append('photos', new File(['Photo 1'], 'photo1.jpg', { type: 'image/jpeg' }));
wrapped.append('photos', new File(['Photo 2'], 'photo2.jpg', { type: 'image/jpeg' }));

// Get all files for a key
const allPhotos = wrapped.getFiles('photos');
console.log(allPhotos.length);  // 2
console.log(allPhotos.map(f => f.name));  // ['photo1.jpg', 'photo2.jpg']
Example 3: Mixed content (files and regular data)
wrapped.username = 'john_doe';
wrapped.age = 30;
wrapped.avatar = new File(['avatar data'], 'avatar.png', { type: 'image/png' });

// Check if property is a file
console.log(wrapped.isFile('avatar'));  // true
console.log(wrapped.isFile('username'));  // false

// Get file info without reading content
const fileInfo = wrapped.getFileInfo('avatar');
console.log(fileInfo);  // [{ name: 'avatar.png', size: 11, type: 'image/png' }]
Example 4: Working with either object or FormData
function processUserData(data: Record<string, any> | FormData) {
  const wrapped = createWrapper(data);
  
  // These operations work for both types
  wrapped.name = 'Jane Doe';
  wrapped.email = '[email protected]';
  
  // Handle file upload (works differently based on type)
  const profilePic = new File(['pic'], 'profile.jpg', { type: 'image/jpeg' });
  wrapped.profilePicture = profilePic;
  
  // Check if we have a file
  if (wrapped.isFile('profilePicture')) {
    const file = wrapped.getFile('profilePicture');
    console.log(`Uploaded file: ${file?.name}, Size: ${file?.size} bytes`);
  }
  
  // Convert to object for processing
  const obj = wrapped.toObject();
  console.log('Data keys:', Object.keys(obj));
  
  return wrapped;
}
Example 5: Real-world form submission scenario
function handleFormSubmit(formElement: HTMLFormElement) {
  const formData = new FormData(formElement);
  const wrapped = createWrapper(formData);
  
  // Add timestamp
  wrapped.submittedAt = Date.now();
  
  // Validate files
  const uploadedFiles = wrapped.getFiles('documents');
  const maxSize = 5 * 1024 * 1024; // 5MB
  
  for (const file of uploadedFiles) {
    if (file.size > maxSize) {
      console.error(`File ${file.name} exceeds maximum size`);
      wrapped.delete('documents');
      wrapped.error = 'File too large';
    }
  }
  
  // Add computed property
  wrapped.fileCount = uploadedFiles.length;
  
  // Get the modified FormData for submission
  const finalFormData = wrapped.getRawData() as FormData;
  
  // Submit with fetch
  fetch('/api/submit', {
    method: 'POST',
    body: finalFormData
  });
}
Example 6: Type-safe file handling
interface UserProfile {
  name: string;
  email: string;
  avatar?: File;
  documents?: File[];
}

function createUserProfile(data: UserProfile | FormData) {
  const wrapped = createWrapper(data);
  
  // Type-safe access
  const name: string = wrapped.name;
  const avatar: File | null = wrapped.getFile('avatar');
  const docs: File[] = wrapped.getFiles('documents');
  
  // Process files
  if (avatar) {
    console.log(`Avatar: ${avatar.name} (${avatar.type})`);
  }
  
  docs.forEach((doc, index) => {
    console.log(`Document ${index + 1}: ${doc.name}`);
  });
  
  return wrapped.toObject();
}

(back to top)

Support

The team is always here to help you. Happen to face an issue? Want to report a bug? You can submit one here on Github using the Issue Tracker. If you still have any questions, please contact us via the Telegram Bot or join in the Global Developer Community on Telegram.

(back to top)

Contributing

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

Credits

(back to top)

License

The MIT License (MIT). Please see License File for more information.

(back to top)

版本与发布记录

@salla.sa/base 共发布 868 个版本,首次发布于 2022/09/11;过去 12 个月发布了 325 个版本。

版本发布日期距今
3.0.21latest2026/11/021 天前
3.0.202026/11/021 天前
3.0.192026/11/021 天前
3.0.182026/11/012 天前
3.0.172026/10/295 天前
3.0.162026/10/285 天前

其他发布通道:canary → 2.8.1-alpha.0,beta → 3.0.0-beta.1。

关于 @salla.sa/base 的常见问题

@salla.sa/base 是什么?

萨拉基

如何安装 @salla.sa/base?

在项目目录运行 npm install @salla.sa/base,或使用 pnpm add / yarn add / bun add。

@salla.sa/base 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@salla.sa/base 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@salla.sa/base 可以商用吗?

@salla.sa/base 使用 GPL-3.0 许可。强 Copyleft:分发包含该代码的软件时,整个作品需以 GPL-3.0 兼容许可开源,并附带专利与反锁定条款。仅内部使用不触发此义务。以上为概括,不构成法律意见,请以许可原文为准。

@salla.sa/base 还在维护吗?

最新版本 3.0.21 发布于 2026/11/02(1 天前);至今共发布 868 个版本,其中过去 12 个月发布了 325 个;首次发布于 2022/09/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。